diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 0c691a9..0344786 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -14,7 +14,12 @@ jobs: matrix: os: [ubuntu-latest] python: ["3.9", "3.10", "3.11", "3.12", "3.13"] + exclude: + - os: ubuntu-latest + python: "3.9" include: + - os: ubuntu-24.04 + python: "3.9" - os: macos-latest python: "3.13" runs-on: ${{ matrix.os }} @@ -25,6 +30,13 @@ jobs: with: python-version: ${{ matrix.python }} + - name: Install the optional genome aligner (filter-paralogs tests) + run: | + # mappy has no wheel for this macOS Python, and its source does not compile as the + # universal (arm64 + x86_64) binary that setup-python's interpreter asks for. + if [ "$RUNNER_OS" = "macOS" ]; then export ARCHFLAGS="-arch $(uname -m)"; fi + python -m pip install mappy + - name: Run tests run: python -m unittest discover -s tests -v diff --git a/.gitignore b/.gitignore index 9c780c5..1c71d17 100644 --- a/.gitignore +++ b/.gitignore @@ -185,3 +185,6 @@ docs/book/ # macOS .DS_Store examples/madcats-demo/results/ + +# minimap2 indexes built by filter-paralogs +*.mmi diff --git a/README.md b/README.md index ed0b367..e580c40 100644 --- a/README.md +++ b/README.md @@ -7,47 +7,48 @@ **Marker-Anchored Discovery and Counting of Alleles from Targeted Sequencing.** -`madcats` is a command-line tool that turns targeted-sequencing FASTQs into +`madcats` is a command-line tool that converts targeted-sequencing FASTQ files into [MADC](https://softwarehub.breedinginsight.org/learn/what-is-a-madc-file.html) microhaplotype count tables. A MADC (Missing Allele Discovery Counts) table records the read count of every -microhaplotype in every sample. A microhaplotype is the short sequence a marker amplifies, so a -marker can have more than two alleles, and the variants beside its target SNP are kept. `madcats` -counts the alleles a panel was designed for and finds additional ones in the reads. +microhaplotype across all samples. Because a microhaplotype captures the full target window +amplified by a marker, a locus can carry more than two alleles while retaining secondary variants +alongside the target SNP. `madcats` counts the designed alleles in a panel and discovers additional +microhaplotypes directly from the reads. -The output is a raw MADC table. It goes through HapApp, which assigns fixed allele IDs for building -a microhaplotype database and comparing sequencing runs. For existing downstream pipelines, a MADC -converts to a VCF of SNP genotype calls, with -[BIGr and updog](https://softwarehub.breedinginsight.org/learn/madc-to-vcf.html) after HapApp. +`madcats` produces a raw MADC table. Downstream workflows typically pass this table through HapApp, +which assigns fixed allele IDs to support cross-project microhaplotype databases. For SNP-based +genotyping pipelines, the HapApp output can then be converted to a VCF and genotyped with +[BIGr and updog](https://softwarehub.breedinginsight.org/learn/madc-to-vcf.html). -`madcats` handles DArTag, AgriSeq (Ion Torrent), GT-seq, rhAmpSeq and Flex-Seq capture data. -It needs only the Python 3 standard library. Every analysis threshold can be adjusted via a command-line option, and -each run writes a JSON file with its parameters and read counts processed during the analysis run. +The same codebase supports DArTag, AgriSeq (Ion Torrent), GT-seq, rhAmpSeq, and Flex-Seq capture +data using only the Python 3 standard library. Every analysis threshold is exposed as a command-line +option, and each run writes a QC JSON file recording its parameters and per-sample read accounting. -> **A prior MADC is not an input.** Generation uses only the FASTQs plus the assay design: the -> DArTag primer/probe files, a probe design alone, or a platform-neutral Ref/Alt tag csv. +> **A prior MADC is not required.** Generation uses only the FASTQ files and the assay design, +> provided as DArTag primer and probe files, a probe design alone, or a platform-neutral Ref/Alt +> reference-tag CSV. ## Highlights -- Closely matches vendor output: read counts correlate at r = 0.9997 with the DArT MADC on a - sweetpotato DArTag panel, and dosage calls agree 95–99% across five DArTag panels. -- Designed to be platform independent, with testing performed on DArTag, GT-Seq, rhAmpSeq, Flex-Seq, and AgriSeq. -- Builds the panel from vendor design files (`madcats design`), from the probe design and the reads - when there is no primer file (`madcats infer-design`), or from your own Ref/Alt tag CSV. -- Reports a new microhaplotype only when several samples carry it, one sample has many reads of it, - or (optionally) it has enough high-quality reads. -- Merges sequencing errors back into the alleles they came from, without changing any sample's - Ref/Alt dosage. -- Handles indels, including ones the panel was not designed for. -- Works with AgriSeq-style reads that don't start at a primer (`madcats normalize-reads`) and with - paired-end reads (`madcats merge-pairs`). -- Writes raw MADC tables for HapApp, which prepares them for BIGr and other tools. Each row also - lists its variants and marker type. -- Runs samples in parallel and caches per-sample results, so reruns are fast. +- Closely matches vendor output, with r = 0.9997 read-count correlation against the DArT MADC on a + sweetpotato DArTag panel and 95–99% dosage agreement across five DArTag panels. +- Builds the panel definition from vendor design files (`madcats design`), infers it from the probe + design and reads when no primer file is available (`madcats infer-design`), or accepts a curated + Ref/Alt reference-tag CSV directly. +- Reports novel microhaplotypes only when they are reproducible across samples, reach high depth in + a single sample, or (optionally) pass a whole-tag base-quality threshold. +- Merges sequencing errors back into their parent alleles while protecting canonical and + evidence-passing alleles and restricting pooled merges to the same target allele. +- Handles both designed indels and novel undesigned indels through gapped alignment. +- Supports non-primer-started reads such as AgriSeq (`madcats normalize-reads`) and paired-end reads + (`madcats merge-pairs`). +- Includes an optional genome-based paralog filter (`madcats filter-paralogs`, experimental, requires + `pip install 'madcats[genome]'`) for panels where co-amplified paralogs inflate + heterozygosity. It works on MADCATS, vendor, and HapApp fixed-allele-ID MADCs. +- Processes samples in parallel and caches per-sample assignment results for fast reruns. ## Installation -### From PyPI (Recommended) - Requires Python 3.9 or newer. ```bash @@ -55,36 +56,11 @@ pip install madcats madcats --help ``` -To keep it isolated from other Python packages, use [pipx](https://pipx.pypa.io/): -`pipx install madcats`. - -### Pre-built Binaries - -Standalone executables that need no Python installation are attached to each -[release](https://github.com/Breeding-Insight/MADCATS/releases): -- `madcats-linux-x86_64.tar.gz`: Linux -- `madcats-macos-x86_64.tar.gz`: macOS (Intel) -- `madcats-macos-aarch64.tar.gz`: macOS (Apple Silicon) - -```bash -# Download and extract (example: Linux) -curl -LO https://github.com/Breeding-Insight/MADCATS/releases/latest/download/madcats-linux-x86_64.tar.gz -tar -xzf madcats-linux-x86_64.tar.gz -./madcats --help - -# Optional: install to PATH -mkdir -p ~/bin && mv madcats ~/bin/ -# Add to PATH if not already (add to ~/.bashrc or ~/.zshrc): -# export PATH="$HOME/bin:$PATH" -``` - -### From Source - -```bash -git clone https://github.com/Breeding-Insight/MADCATS.git -cd MADCATS -pip install . # or: python3 madcats.py --help (no install needed) -``` +Each [release](https://github.com/Breeding-Insight/MADCATS/releases) also has standalone executables +for Linux and macOS that need no Python. See +[Installation](https://madcats.readthedocs.io/en/latest/getting-started/installation.html) for +those, for `pipx`, for running from a clone, and for the optional aligner that `filter-paralogs` +needs. ## Quick Start @@ -110,37 +86,25 @@ madcats validate \ --generated results/project_MADC.csv \ --expected vendor_MADC.csv \ --report results/validation.json -``` -No primer file? Infer the panel from the probe design and the reads: - -```bash -madcats infer-design \ - --probe-design panel_probe-design.txt \ - --fastq-dir fastqs/ \ - --output reference_tags.csv ``` -Reads that are not primer-started (for example AgriSeq on Ion Torrent) are normalized first: - -```bash -madcats normalize-reads --probe-design markers.tsv --fastq-dir raw_fastqs/ --out-dir normalized/ --jobs 8 -madcats generate --fastq-dir normalized/ --fastq-glob "*.fastq" \ - --reference-tags normalized/window_reference_tags.csv \ - --tag-length 41 --min-supporting-freq 0.10 --output project_MADC.csv -``` +The tutorials cover the other routes, which are panels +[without a primer file](https://madcats.readthedocs.io/en/latest/tutorials/primer-free.html), +[AgriSeq and other reads that do not start at a primer](https://madcats.readthedocs.io/en/latest/tutorials/agriseq.html) +and [paired-end reads](https://madcats.readthedocs.io/en/latest/tutorials/paired-end.html). ## Documentation Full documentation is available at [madcats.readthedocs.io](https://madcats.readthedocs.io), including: -- [Getting Started](https://madcats.readthedocs.io/en/latest/getting-started/installation.html): installation and first steps -- [Tutorials](https://madcats.readthedocs.io/en/latest/tutorials/dartag.html): walkthroughs for DArTag, primer-free, AgriSeq and paired-end data -- [Command Reference](https://madcats.readthedocs.io/en/latest/commands/overview.html): every subcommand and option -- [Evidence Model](https://madcats.readthedocs.io/en/latest/reference/evidence-model.html): how alleles are counted, discovered and denoised +- [Getting Started](https://madcats.readthedocs.io/en/latest/getting-started/installation.html) for installation and first steps +- [Tutorials](https://madcats.readthedocs.io/en/latest/tutorials/dartag.html) with step-by-step examples for DArTag, primer-free, AgriSeq, and paired-end data, plus the paralog filter +- [Command Reference](https://madcats.readthedocs.io/en/latest/commands/overview.html) for every subcommand and option +- [Evidence Model](https://madcats.readthedocs.io/en/latest/reference/evidence-model.html) on how MADCATS counts, discovers, and denoises alleles -The design rationale and version-by-version measurements behind every default are recorded in the -[development record](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md). +The [development record](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md) +documents the design rationale and version-by-version benchmarks behind each default. ## Commands @@ -149,56 +113,43 @@ The design rationale and version-by-version measurements behind every default ar | `madcats design` | Reconstruct Ref/Alt tags from vendor primer + probe-design files | | `madcats infer-design` | Infer a reference-tag panel from the probe design plus FASTQ evidence | | `madcats merge-pairs` | Merge overlapping paired-end reads into single fragments | -| `madcats normalize-reads` | Orient and window non-primer-started amplicon reads (e.g. AgriSeq) | -| `madcats window-scan` | Sweep candidate tag lengths and recommend one from the project's own reads | +| `madcats normalize-reads` | Orient and window non-primer-started amplicon reads (e.g., AgriSeq) | +| `madcats window-scan` | Sweep candidate tag lengths and recommend one from the project's reads | | `madcats generate` | Generate the MADC count table | | `madcats validate` | Compare a generated MADC against a reference MADC | +| `madcats filter-paralogs` | Drop or flag MADC rows that a reference genome places at another locus (experimental, requires `mappy`) | -Run `madcats --help` for full options. - -## Input Formats - -### Reference tags (CSV) -The platform-neutral panel definition that `generate` consumes. Produced by `design`, -`infer-design` or `normalize-reads`, or curated by hand. -``` -MarkerName,LeftPrimerSequence,RefSequence,AltSequence -Chr01_000123,ACGTTGCAGGTCAAGT,ACGTTGCAGGTCAAGTTCA...,ACGTTGCAGGTCAAGTTCG... -``` -`VariantPositionInTagSequence`, `VariantRef`, `VariantAlt`, `RightPrimerSequence` and -`LocusGroup` are optional. - -### Probe design (TSV/CSV) -`MarkerName` and `TargetSequence` with one bracketed variant: a SNP such as `[C/T]` or an -anchored indel such as `[A/ACTTG]`. - -### FASTQs -One FASTQ (optionally gzipped) per sample in a folder. Sample columns are named by the FASTQ stem, -or by a `--sample-lookup` table. +Run `madcats --help` for full options. `filter-paralogs` is new in 0.14.0 and is marked +experimental, so its options, defaults, and outputs may change in future releases. -## Output +## Input and Output -| File | Contents | -|------|----------| -| `project_MADC.csv` | MADC table: `AlleleID`, `CloneID`, `AlleleSequence`, summary columns, one read-count column per sample | -| `project_MADC.csv.qc.json` | Parameters, provenance, and per-sample read accounting | -| `project_MADC.csv.variants.csv` | One line per variant event per row (with `--annotations on`, the default) | +`generate` takes one FASTQ file per sample (plain or gzipped) and a reference-tag CSV panel +definition generated by `design`, `infer-design`, `normalize-reads`, or curated manually. It writes +the MADC count table, a QC JSON file with run parameters and per-sample read accounting, and a +sidecar CSV listing each row's variants. See +[Input Formats](https://madcats.readthedocs.io/en/latest/getting-started/input-formats.html) and +[Output Formats](https://madcats.readthedocs.io/en/latest/reference/output-formats.html). Breeding +Insight's [MADC file format overview](https://softwarehub.breedinginsight.org/learn/what-is-a-madc-file.html) +describes the table's columns. ## Validation -Each platform was checked against the best independent comparison available for its dataset. -"Genotype agreement" means updog dosage calls made from the MADCATS table (through HapApp and BIGr) -compared with the reference genotypes. +Each platform was evaluated against the best independent comparison available for its dataset. +"Genotype agreement" refers to updog dosage calls generated from the MADCATS table (via HapApp and +BIGr) compared with independent reference genotypes. | Platform | Accuracy | Validated against | |----------|----------|-------------------| -| DArTag (sweetpotato, red clover, blackberry, alfalfa, pecan) | count r = 0.9997; dosage agreement 95.4–98.8% | vendor MADC, vendor/updog dosage, families, skim-seq VCF | -| AgriSeq, Ion Torrent (honeybee, oyster) | 94.9% vs Torrent VariantCaller; 98.0% replicate concordance | vendor caller + replicates | +| DArTag (sweetpotato, red clover, blackberry, alfalfa, pecan) | count r = 0.9997, dosage agreement 95.4–98.8% | vendor MADC, vendor/updog dosage, families, skim-seq VCF | +| AgriSeq, Ion Torrent (honeybee, oyster) | 94.9% vs Torrent VariantCaller, 98.0% replicate concordance | vendor caller + replicates | | GT-seq (delta smelt) | 99.49% | independent BWA/bcftools truth VCF | | Flex-Seq capture (cranberry) | 95.13% genotype agreement | published population VCF + 20 trios | | rhAmpSeq (8 grape families) | 99.92–99.99% family transmission | Mendelian constraints + same-reads head-to-head | + > Important Note: MADCATS has been tested on several published and unpublished DArTag species panels. For the performance across the other targeted genotyping platforms, additional validation is needed on available data. -Details: [Validation & Accuracy](https://madcats.readthedocs.io/en/latest/reference/validation.html). + +See [Validation & Accuracy](https://madcats.readthedocs.io/en/latest/reference/validation.html) for details. ## Development @@ -216,12 +167,9 @@ If MADCATS is useful in your work, please cite: > Sandercock, A.M. (2026). MADCATS: Marker-Anchored Discovery and Counting of Alleles from Targeted > Sequencing. GitHub repository: https://github.com/Breeding-Insight/MADCATS -*(A formal article/DOI is planned; this section will be updated when available.)* - -For the MADC format, see Breeding Insight's -[MADC file format overview](https://softwarehub.breedinginsight.org/learn/what-is-a-madc-file.html). +*(A formal article/DOI is planned, and this section will be updated when available.)* -**AI assistance:** MADCATS was developed in collaboration with Claude Opus 5.5 and Fable 5.1 +**AI assistance.** MADCATS was developed in collaboration with Claude Opus 5.5 and Fable 5.1 (Anthropic), which helped write its code and documentation. The authors directed the work, reviewed and tested the results, and are ultimately responsible for the application. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 9519c80..1233064 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -2,11 +2,11 @@ **Marker-Anchored Discovery and Counting of Alleles from Targeted Sequencing** -> This is the long-form development record: design rationale, version-by-version +> This long-form development record holds design rationale, version-by-version > changes, and the measurements behind every default. It was the project README > through 0.12.1. For installation and everyday usage, start with the > [README](../README.md) or the [documentation site](https://madcats.readthedocs.io). -> Command examples below use `python3 madcats.py`; after `pip install madcats` +> Command examples below use `python3 madcats.py`. After `pip install madcats` > the same commands run as `madcats `. A platform-independent tool for recovering design-specified alleles and @@ -18,97 +18,103 @@ origins as a FASTQ-to-MADC workflow, where MADC denotes the Missing Allele Discovery Counts format.) **A prior MADC is not an input to the workflow.** Generation uses the FASTQs -plus the assay design: either the DArTag primer/probe files or a +plus the assay design, either the DArTag primer/probe files or a platform-neutral Ref/Alt tag manifest. -Every generation run consumes one panel definition: a platform-neutral +Every generation run consumes one panel definition, a platform-neutral reference-tag CSV holding each marker's primer-started, fixed-length Ref and Alt tag sequences. Three routes produce that definition, differing only in which inputs they require: -1. **Design route** (`design` command): the vendor's primer CSV plus the - bracket-notation probe-design file. Deterministic reconstruction from - design files alone — no sequencing data involved. Use when both files - are available; it is the reference implementation the other routes are - validated against. A tag is the primer-started window that carries the - bracketed variant, so a primer occurrence in a duplicated flank that - never reaches the variant is not a candidate (the pecan 3K panel has one - such marker; before this rule it was reported as ambiguous). Any DArT +1. **Design route** (`design` command). It takes the vendor's primer CSV + plus the bracket-notation probe-design file and reconstructs the tags + deterministically from these design files alone, with no sequencing + data involved. Use when both files are available. It is the reference + implementation for validating the other routes. A tag is the + primer-started window that carries the bracketed variant, so a primer + occurrence in a duplicated flank that never reaches the variant is not + a candidate (the pecan 3K panel has one such marker, which this route + reported as ambiguous before the rule). Any DArT marker table with `MarkerName` and a bracket-notation `TargetSequence` serves as the probe design, extra markers and columns included. Raw DArT deliveries (older orders) keep an inline barcode and the - library's common sequence `GATGGATCCAGTGC` in front of every amplicon; + library's common sequence `GATGGATCCAGTGC` in front of every amplicon. `--leading-anchor GATGGATCCAGTGC` cuts each read where that sequence ends (it must end within 40 bases beyond its own length) and counts - reads without it as `reads_no_leading_anchor`. Preprocessed deliveries + reads without it as `reads_no_leading_anchor`. With + `--leading-anchor-mismatches 1` (0.14.0; the default is `0`), a read with no + exact copy is cut after its one placement within a single substitution + and counted as `reads_leading_anchor_mismatch`. Preprocessed deliveries are primer-started and need no anchor. The anchor is part of the cache - key and the provenance line; `infer-design` takes the same option, so - the primer-free route reads raw deliveries too. Both commands check the - first FASTQ before any read pass: when almost no read starts with a - panel tag but most carry one after a constant prefix, the run stops and - names that prefix (the suffix shared by the bases in front of the tag), + key and the provenance line. `infer-design` takes `--leading-anchor` + as well, so the primer-free route reads raw deliveries too. Both commands + check a sample of the FASTQs (up to 24, spread across the run) before + any read pass. When almost no read starts with a panel tag but most + carry one after a constant prefix, the run stops and names that prefix + (the suffix that the sampled files' prefixes share), and `--leading-anchor auto` applies the detected sequence instead, recording it in the QC as detected. -2. **Vendor-MADC bootstrap** (`scripts/madc_to_reference_tags.py`): any - delivered MADC from the same panel. The vendor's canonical Ref/Alt rows - carry the exact tags, their first difference gives the variant position, - and a tag prefix substitutes for the primer as the assignment anchor. - Use when a prior vendor report exists but design files are private; the - result reproduces the vendor's tags exactly, including their IUPAC - curation. Markers that cannot become loci — above all Ref and Alt rows +2. **Vendor-MADC bootstrap** (`scripts/madc_to_reference_tags.py`). It + takes any delivered MADC from the same panel. The vendor's canonical + Ref/Alt rows carry the exact tags, their first difference gives the + variant position, and a tag prefix substitutes for the primer as the + assignment anchor. Use when a prior vendor report exists but design + files are private. The result reproduces the vendor's tags exactly, + including their IUPAC curation. The script announces markers that + cannot become loci with a `WARNING:` per reason and lists them with + their reason in `OUTPUT.skipped.tsv`. The main case is Ref and Alt rows that carry the same sequence, which means the target lies one base past - the window (or the design is presence/absence) — are announced with a - `WARNING:` per reason and listed with their reason in - `OUTPUT.skipped.tsv`; on one DArTag project that was 46 of 3,086 - markers, invisible until the sidecar existed. -3. **Primer-free inference** (`infer-design` command): the probe-design - file plus the project's own FASTQs, with the primer file never consulted. - Candidate tag windows are enumerated from the design targets and - selected by exact read-prefix votes (an identity-envelope fuzzy pass - covers loci with no exact support). Use when the primer file is withheld - and no vendor MADC exists; accuracy is measured per project in the - validation sections below. + the window (or the design is presence/absence). On one DArTag project + that was 46 of 3,086 markers, invisible until the sidecar existed. +3. **Primer-free inference** (`infer-design` command). It takes the + probe-design file plus the project's own FASTQs and never consults the + primer file. It enumerates candidate tag windows from the design + targets and selects among them by exact read-prefix votes (an + identity-envelope fuzzy pass covers loci with no exact support). Use + when the primer file is withheld and no vendor MADC exists. The + validation sections below measure its accuracy per project. A hand-curated CSV from any other source (for example a public panel -database) is equally valid input — the reference-tags CSV is the contract, -not its producer. +database) is equally valid input, because the reference-tags CSV is the +contract, not its producer. -Platforms whose reads are not primer-started take one extra stage first: +Platforms whose reads are not primer-started take one extra stage first. `normalize-reads` locates each raw read against the probe-design targets by k-mer, orients it forward, and excises a fixed tag-length window containing the variant, emitting pipeline-ready per-sample FASTQs together with the matching window reference-tags CSV and a QC ledger. The window is the -platform-neutral substitute for a primer-defined tag; after normalization, +platform-neutral substitute for a primer-defined tag. After normalization, generation runs unchanged. Because the window is an analytical choice rather than a physical one, every later run of the same panel should pass -`--reuse-tags` with the first run's window CSV — freezing placement is -what keeps microhaplotype sequences comparable across sequencing runs. +`--reuse-tags` with the first run's window CSV. Freezing placement keeps +microhaplotype sequences comparable across sequencing runs. See the AgriSeq pathway section below. -Paired-end platforms add one geometry decision before normalization — -merge overlapping pairs (`merge-pairs`) or pool non-overlapping mates — -and panels may tile several windows onto one locus (`LocusGroup`); both -are 0.9.0 features documented in their own section below. Adapter -trimming is not required on any route: reads are located middle-out, and -adapter content beyond the fragment cannot enter a fully covered window. +Paired-end platforms add one geometry decision before normalization, +which is to merge overlapping pairs (`merge-pairs`) or pool +non-overlapping mates. Panels may also tile several windows onto one +locus (`LocusGroup`). Both are 0.9.0 features with their own section +below. No route requires adapter trimming, because reads are located +middle-out, and adapter content beyond the fragment cannot enter a fully +covered window. ## Performance at a glance -Five platforms validated through one engine, each against the strongest +One engine covers five platforms, each validated against the strongest comparator its data permits. "Usable windows" is the fraction of raw -reads that survive to clean, counted evidence at a panel window (see -the read-accounting guardrails below — some loss is correct rejection -of off-target and dimer reads, and external pipelines' percentages use -different denominators). +reads that survive filtering to become counted evidence at a panel +window (see the read-accounting guardrails below). Some loss is correct +rejection of off-target and dimer reads, and external pipelines' +percentages use different denominators. | platform (dataset) | reads -> usable windows | accuracy | validated against | |---|---|---|---| -| DArTag (hexaploid sweetpotato; diploid red clover; mixed-ploidy blackberry) | 56.5% of delivered records — vs the vendor's own 50.9% on the same FASTQs (19.6% of records are shorter than the 81-bp tag and unusable by any pipeline) | red clover 3-bin dosage agreement **96.98%** with the vendor table (DP>=20, 682,226 cells, 0.11.0; updog on both tables 99.73% at DP>=10, 0.9.x); sweetpotato count correlation r=0.9997 on 1.20M shared-row cells (0.11.0); blackberry dosage agreement 95.39% (967,299 cells); blackberry design tags 3,015/3,015 match the vendor canonicals (2,881 identical, 134 differ only by the vendor's IUPAC codes); alfalfa panel-paper validation set (two 2021 orders, 54-bp design, raw deliveries cut at the common sequence, 0.12.0): category agreement 99.60% and 99.83%, dosage agreement 98.40% and 97.40%, F1 and BC1 progeny haplotypes within the parental sets at 98.6–98.7% (vendor table 98.9%); pecan 3K (2023 order, 81-bp design, 0.12.0): category agreement 98.89%, dosage agreement **98.78%** on 1.02M cells, F1 progeny haplotypes within the parental set at 99.82% (vendor 99.86%), 93.3% agreement with skim-sequencing genotypes on 11 shared cultivars (vendor 93.3%) | vendor MADC + vendor/updog dosage calls + families + skim-sequencing VCF | -| AgriSeq, Ion Torrent (2 honeybee chips; 372-sample oyster) | 88.4% | **94.9%** vs Torrent VariantCaller (152,698 cells; core 97.8%; 94.5% before 0.10.0's indel recovery); honeybee replicate concordance **98.0%**, cross-chip 98.2% | vendor caller + replicates | -| GT-seq (96-sample delta smelt) | 84.5% merged | **99.49%** R1-only (98.80% before 0.10.0 — the gain is one real insertion allele the fixed-offset reading misclassified); 98.67% with tiles on +54% cells; end-of-chain (HapApp->BIGr->updog) **98.42%** targets + **98.79%** on 38K off-target SNPs; `infer-design` 368/368 primer-free | independent BWA/bcftools truth VCF | -| Flex-Seq capture (192-sample cranberry) | 81.9% (110-bp windows) | end-of-chain **95.13%** targets (295,068 cells); trio incompatibility **3.6%** vs 6.2% for the comparison VCF's own source; locus recovery 80.7%/99.84% vs vendor 83.1%/99.8% | published population VCF + 20 pedigree trios | -| rhAmpSeq (608 runs, 8 biparental grape families) | 86.6% (cohort-discovery panel; 79.3% on the original 16-sample-discovery panel) | family transmission **99.92-99.99%** (~14.9K locus-family tests); head-to-head vs the platform's own `analyze_amplicon` pipeline on identical reads: **93.0%** exact haplotype-genotype agreement, +19%/+79% more callable cells at 10x/30x, and MADCATS is the more Mendelian-consistent of the pair (99.947% vs 99.850% within the inferred parental four). Cohort-scale discovery (per-family union across all 8 families) designs 1,993/2,000 panel amplicons and delivers +43% genotype calls over the subset-discovery panel at held three-nines transmission, with every added locus 100.000% family-consistent (84,757 calls, zero violations) | Mendelian family constraints + same-reads tool head-to-head (no public truth matrix) | -| synthetic truth suite | — | dosage **100%** on clean/linked/paralog/repeat classes; 50.8% on engineered null alleles (the correct negative); paired-end merge 100% with 98.6% molecular recovery | exact simulated truth | +| DArTag (hexaploid sweetpotato, diploid red clover, mixed-ploidy blackberry) | 56.5% of delivered records, against the vendor's own 50.9% on the same FASTQs (19.6% of records are shorter than the 81-bp tag and unusable by any pipeline) | Red clover 3-bin dosage agreement with the vendor table is 96.98% (DP>=20, 682,226 cells, 0.11.0), and updog on both tables agrees at 99.73% (DP>=10, 0.9.x). Sweetpotato count correlation is r=0.9997 on 1.20M shared-row cells (0.11.0). Blackberry dosage agreement is 95.39% (967,299 cells), and blackberry design tags match the vendor canonicals at 3,015/3,015 (2,881 identical, 134 differ only by the vendor's IUPAC codes). The alfalfa panel-paper validation set (two 2021 orders, 54-bp design, raw deliveries cut at the common sequence, 0.12.0) has category agreement 99.60% and 99.83%, dosage agreement 98.40% and 97.40%, and F1 and BC1 progeny haplotypes within the parental sets at 98.6–98.7% (vendor table 98.9%). Pecan 3K (2023 order, 81-bp design, 0.12.0) has category agreement 98.89%, dosage agreement 98.78% on 1.02M cells, F1 progeny haplotypes within the parental set at 99.82% (vendor 99.86%), and 93.3% agreement with skim-sequencing genotypes on 11 shared cultivars (vendor 93.3%) | vendor MADC + vendor/updog dosage calls + families + skim-sequencing VCF | +| AgriSeq, Ion Torrent (2 honeybee chips, 372-sample oyster) | 88.4% | 94.9% vs Torrent VariantCaller (152,698 cells, core 97.8%, 94.5% before 0.10.0's indel recovery), and honeybee replicate concordance 98.0%, cross-chip 98.2% | vendor caller + replicates | +| GT-seq (96-sample delta smelt) | 84.5% merged | 99.49% R1-only (98.80% before 0.10.0, a gain from one real insertion allele the fixed-offset reading misclassified), 98.67% with tiles on +54% cells, end-of-chain (HapApp->BIGr->updog) 98.42% targets + 98.79% on 38K off-target SNPs, and `infer-design` 368/368 primer-free | independent BWA/bcftools truth VCF | +| Flex-Seq capture (192-sample cranberry) | 81.9% (110-bp windows) | end-of-chain 95.13% targets (295,068 cells), trio incompatibility 3.6% vs 6.2% for the comparison VCF's own source, and locus recovery 80.7%/99.84% vs vendor 83.1%/99.8% | published population VCF + 20 pedigree trios | +| rhAmpSeq (608 runs, 8 biparental grape families) | 86.6% (cohort-discovery panel, 79.3% on the original 16-sample-discovery panel) | family transmission 99.92-99.99% (~14.9K locus-family tests). Head-to-head against the platform's own `analyze_amplicon` pipeline on identical reads, MADCATS reaches 93.0% exact haplotype-genotype agreement, +19%/+79% more callable cells at 10x/30x, and the more Mendelian-consistent calls of the pair (99.947% vs 99.850% within the inferred parental four). Cohort-scale discovery (per-family union across all 8 families) designs 1,993/2,000 panel amplicons and delivers +43% genotype calls over the subset-discovery panel at held three-nines transmission, with every added locus 100.000% family-consistent (84,757 calls, zero violations) | Mendelian family constraints + same-reads tool head-to-head (no public truth matrix) | +| synthetic truth suite | — | dosage 100% on clean/linked/paralog/repeat classes, 50.8% on engineered null alleles (the correct negative), and paired-end merge 100% with 98.6% molecular recovery | exact simulated truth | Version 0.10.0 adds recovery of *undesigned* indel haplotypes through a general gapped reading (see its section below). On a private in-house @@ -117,49 +123,52 @@ that the vendor MADC lacked, 78% became MADC rows at 97% read recall (0.4% under 0.9.x), and the SNP calls on every truth-scored set above held or improved. -Accuracy tracks comparator quality more than platform: where truth is -clean (GT-seq, DArTag) MADCATS scores 98-99%+; against noisier -comparators (TVC, raw mpileup) the *mutual* agreement is 94-95% while +Accuracy tracks comparator quality more than platform. Where the truth +set is reliable (GT-seq, DArTag), MADCATS scores 98-99%+. Against noisier +comparators (TVC, raw mpileup) the *mutual* agreement is 94-95%, while internal instruments (replicates, trios) show MADCATS' own calls at the -cleaner end of each pair — on cranberry, measurably more +more accurate end of each pair. On cranberry they are measurably more Mendelian-consistent than the raw calls behind the comparison VCF. ## Important scope -DArT describes its analytical pipeline as proprietary. Exact vendor -equivalence therefore cannot be guaranteed because its adapter/quality -filtering, partial-read handling, consensus construction, and error-correction -rules are not documented. This implementation is an open and deterministic -replacement, not a claim to be DArT's undisclosed implementation. - -The generated file preserves the MADC fields needed for microhaplotype work: -`AlleleID`, `CloneID`, `AlleleSequence`, `ClusterConsensusSequence`, and one -integer read-count column per sample, following the vendor conventions +DArT describes its analytical pipeline as proprietary. MADCATS therefore +cannot guarantee exact vendor equivalence, because DArT does not document +its adapter/quality filtering, partial-read handling, consensus +construction, and error-correction rules. This implementation is an open +and deterministic replacement, not a claim to be DArT's undisclosed +implementation. + +The generated file preserves the MADC fields needed for microhaplotype work, +which are `AlleleID`, `CloneID`, `AlleleSequence`, +`ClusterConsensusSequence`, and one integer read-count column per sample, +following the vendor conventions observed in the supplied report (canonical rows carry their own sequence as -the consensus; Match/Other rows carry the Ref consensus). `AvgCountRef` and -`AvgCountSnp` are nonzero means, and `CallRate` is filled with the fraction of +the consensus, and Match/Other rows carry the Ref consensus). `AvgCountRef` and +`AvgCountSnp` are nonzero means, and `CallRate` holds the fraction of samples having canonical Ref or Alt reads at the locus. The remaining vendor dosage/genotype summary fields are downstream calls rather than FASTQ -evidence and are emitted as `.` (missing value; see the output-format -section). +evidence, so the pipeline emits them as `.` (a missing value, described in +the output-format section). -Matching is substitution-only first: reads are compared to same-length -tags at each position. **Designed indel markers are fully supported** — +Matching is substitution-only first, comparing reads to same-length +tags at each position. Designed indel markers are fully supported, because vendors report indel alleles as fixed-length windows whose suffix shifts at the indel, and both tags are ordinary same-length sequences to the counting -layer. Since 0.10.0, **undesigned indels are recovered too**: a read that -frameshifts against every canonical tag is offered one gapped reading under +layer. Since 0.10.0, undesigned indels are recovered too. A read that +frameshifts against every canonical tag gets one gapped reading under the same edit budget (gaps of up to `--max-indel-length` bases, 10 by -default, counted as edits), and is kept as an ordinary fixed-length -shifted-suffix row when that reading is composed like an indel haplotype -(few substitutions, few gap events). The target base is read through the -alignment. Out of scope remain indels longer than the band and gapped -readings that need many substitutions — those are co-amplified paralogs, -not alleles, and stay off-target. +default, count as edits), and the pipeline keeps it as an ordinary +fixed-length shifted-suffix row when that reading has the composition of +an indel haplotype (few substitutions, few gap events). The pipeline reads +the target base through the alignment. Indels longer than the band and +gapped readings that need many substitutions remain out of scope. Those +are co-amplified paralogs, not alleles, and stay off-target. ## Quick start for the supplied sweetpotato project -The defaults are the recommended configuration; no evidence flags are needed: +The defaults are the recommended configuration, so the command needs no +evidence flags: ```bash python3 madcats.py generate \ @@ -172,7 +181,7 @@ python3 madcats.py generate \ ``` A stricter, higher-precision view for high-depth projects raises the -reproducibility depth: add `--reproducible-min-reads 20`. +reproducibility depth with `--reproducible-min-reads 20`. To inspect or reuse the reconstructed 3,120 Ref/Alt tags, run the separate design command: @@ -185,8 +194,8 @@ python3 madcats.py design \ ``` Other targeted platforms can pass this same reference-tag format with -`--reference-tags`. The provided DArT report is used only after generation, -as an external validation target: +`--reference-tags`. The validate command uses the provided DArT report only +after generation, as an external validation target: ```bash python3 madcats.py validate \ @@ -199,104 +208,108 @@ python3 madcats.py validate \ For each marker, the pipeline locates the left primer in the supplied target sequence in either orientation, extracts the primer-started tag, verifies the -target-SNP position, and constructs the Alt tag by substitution. Each FASTQ -read is assigned by its left-primer prefix, retained as a raw full tag of the -configured length (81 bp by default), and accepted when it has at least 80% -substitution-only identity to Ref or Alt — or, when every candidate rejects -it, under one gapped reading that spends the same 20% edit budget -(`--gapped-rescue on`, the default; see the 0.10.0 section). - -Canonical Ref and Alt rows are always emitted, including at zero counts. A -**non-canonical sequence** becomes an output row when it reaches +target-SNP position, and constructs the Alt tag by substitution. It assigns +each FASTQ read by its left-primer prefix, retains it as a raw full tag of +the configured length (81 bp by default), and accepts it when it has at +least 80% substitution-only identity to Ref or Alt, or, when every +candidate rejects it, under one gapped reading that spends the same 20% +edit budget (`--gapped-rescue on`, the default, described in the 0.10.0 +section). + +The pipeline always emits canonical Ref and Alt rows, including at zero +counts. A non-canonical sequence becomes an output row when it reaches `--min-global-count` project-wide reads and passes at least one enabled evidence route: -- **Reproducibility route** (primary; default on): at least +- **Reproducibility route** (primary, default on). It requires at least `--reproducible-min-reads` reads (default 10) in each of at least `--reproducible-min-samples` samples (default 2). Identical 81-mers recurring independently across samples are strong evidence even when a base position is systematically low-quality. -- **Depth route** (default on): at least `--depth-min-reads` reads (default - 30) within a single sample. This keeps private alleles discoverable in - unreplicated designs such as diversity panels of singleton accessions; on - the replicated project below it adds a single row, because deep sequences - there always recur across the paired extracts. -- **Quality route** (default off): at least `--quality-min-clean-reads` reads - whose every tag base is at or above `--discovery-min-quality` (default - Q20). On the supplied project this route's marginal precision was 3% - (2,159 extra rows for 73 additional vendor-matching rows), and whole-tag - cleanliness vetoes real alleles with one systematically low-quality cycle, - so it is no longer a default gate. +- **Depth route** (default on). It requires at least `--depth-min-reads` + reads (default 30) within a single sample. This keeps private alleles + discoverable in unreplicated designs such as diversity panels of + singleton accessions. On the replicated project below it adds a single + row, because deep sequences there always recur across the paired extracts. +- **Quality route** (default off). It requires at least + `--quality-min-clean-reads` reads whose every tag base is at or above + `--discovery-min-quality` (default Q20). On the supplied project this + route's marginal precision was 3% (2,159 extra rows for 73 additional + vendor-matching rows), and whole-tag cleanliness vetoes real alleles + with one systematically low-quality cycle, so it is no longer a default + gate. An optional HaploCharmer-style dosage-aware floor, `--min-supporting-freq` -(default 0 = off), additionally requires a sample's reads for the sequence to +(default 0 = off), also requires a sample's reads for the sequence to reach that share of the sample's locus total before the sample can support the reproducibility or depth route. Measured on the supplied project, a 0.01 floor raises precision 2.2 points and costs 0.35 recall points (17,319 rows, 86.2%/77.2%), but it removes 33 of the vendor-confirmed rows the evidence -redesign recovered: amplicon pools inflated by co-amplified paralogs leave -real minor haplotypes at sub-percent shares, so the floor stays off by -default. It is most useful as an artifact guard on the depth route in -unreplicated designs, where around 0.01 is a reasonable starting point. +redesign recovered, because amplicon pools inflated by co-amplified +paralogs leave real minor haplotypes at sub-percent shares. The floor +therefore stays off by default. It is most useful as an artifact guard on +the depth route in unreplicated designs, where around 0.01 is a +reasonable starting point. Evidence thresholds are absolute read counts and therefore do not scale with sequencing depth. At the honeybee AgriSeq run's ~750x per sample per marker, 10 reads sits below the Ion error noise floor, and the defaults admitted 1,752 novel rows of which roughly 92% were error haplotypes -(median carrier share near zero). Sweep-backed guidance by depth regime: -at low depth (~60x) and at standard DArTag depth the defaults stand; at -very high depth (above roughly 500x per sample per marker) enable -`--min-supporting-freq 0.10` — on the honeybee run it collapsed the novel -rows to 147 while raising caller concordance from 89.8% to 90.6%, and -locus-share floors dominate rescaled absolute thresholds because -per-marker depth varies tenfold within a single run. +(median carrier share near zero). Sweeps back the following guidance by +depth regime. At low depth (~60x) and at standard DArTag depth the +defaults stand. At very high depth (above roughly 500x per sample per +marker), enable `--min-supporting-freq 0.10`. On the honeybee run it +collapsed the novel rows to 147 while raising caller concordance from +89.8% to 90.6%, and locus-share floors dominate rescaled absolute +thresholds because per-marker depth varies tenfold within a single run. Setting every route's threshold to 0 emits every sequence at or above `--min-global-count` (exhaustive discovery). The same rule protects qualifying sequences from abundance-skew denoising and gates partial-read extension, so discovery, protection, and extension stay consistent. Abundance-skew denoising (UNOISE-style, `2^(alpha*d+1)`, closest parent -first) then absorbs low-abundance neighbors within each sample; a pooled +first) then absorbs low-abundance neighbors within each sample. A pooled pass (`--global-denoise-distance`, default 1) afterwards folds an evidence-failing sequence into the protected parent the project-wide skew -names — but only when both carry the same target allele, so no move can +names, but only when both carry the same target allele, so no move can change a sample's Ref/Alt dosage (0.9.x moved reads across alleles, which -could turn a private 25/25 heterozygote into Ref=50). Evidence-passing and -canonical sequences are never absorbed. Reads whose sequences pass no route -remain visible in the QC read accounting rather than silently vanishing. At the default distance of 1 the eligible parents of a sequence are its single-substitution neighbours, which the denoiser enumerates and looks up rather than finding by scanning every centroid; the selection is identical, and a paralogous locus with thousands of unique sequences per sample (the pecan 3K panel has one) no longer makes the pass quadratic. +could turn a private 25/25 heterozygote into Ref=50). The denoiser never +absorbs evidence-passing and canonical sequences. Reads whose sequences +pass no route remain visible in the QC read accounting rather than silently vanishing. At the default distance of 1 the eligible parents of a sequence are its single-substitution neighbours, which the denoiser enumerates and looks up rather than finding by scanning every centroid. The selection is identical, and a paralogous locus with thousands of unique sequences per sample (the pecan 3K panel has one) no longer makes the pass quadratic. -Classification against the design is IUPAC-aware on the design side: with an +Classification against the design is IUPAC-aware on the design side. With an ambiguity-coded design allele, a compatible concrete observed base classifies as RefMatch/AltMatch. An ambiguous observed base such as N is missing data and classifies as Other, matching the vendor's convention. Ref/Alt category assignment and per-row counts always use exact sequence equality, so an -ambiguity-coded canonical tag reports zero exact counts; the pipeline does +ambiguity-coded canonical tag reports zero exact counts. The pipeline does not guess which concrete variants a curated IUPAC consensus was meant to absorb (DArT uses such codes to encode real secondary SNPs, so collapsing -them would merge genuine microhaplotypes — measured on the blackberry -panel). A read whose tag contains an N is never counted as a haplotype of -its own: it is credited to the one N-free sequence at its locus it is -compatible with, or dropped (`reads_n_mapped` / `reads_n_dropped`). - -Reads shorter than the tag length are salvaged by default -(`--partial-read-mode assign`): a trimmed prefix is credited to the one -learned full tag it matches, and only when it is longer than every prefix -shared between two learned alleles of its locus (see the 0.11.0 section +them would merge genuine microhaplotypes, as measured on the blackberry +panel). The pipeline never counts a read whose tag contains an N as a +haplotype of its own. It credits the read to the one N-free sequence at +its locus that the read is compatible with, or drops it +(`reads_n_mapped` / `reads_n_dropped`). + +By default (`--partial-read-mode assign`) the pipeline salvages reads +shorter than the tag length. It credits a trimmed prefix to the one +learned full tag it matches, and only when the prefix is longer than every +prefix shared between two learned alleles of its locus (see the 0.11.0 section "Truncated reads: partial-read salvage with a locus guard"). `off` excludes such -reads. A partial read never establishes an allele: a prefix of nothing -learned is left unmapped. Note that a partial read's quality is judged over +reads. A partial read never establishes an allele, so a prefix of nothing +learned stays unmapped. The pipeline judges a partial read's quality over its observed bases only. ## Recovering a panel without the primer file (`infer-design`) Some providers treat the primer file as proprietary. Its only irreplaceable -content is where each tag starts inside the probe-design target: the tag must +content is where each tag starts inside the probe-design target. The tag must be a tag-length window of the bracket-expanded target containing the SNP, so inference selects among a closed candidate set (~4x tag-length windows per locus) rather than reconstructing sequences freely. Because reads are primer-started, exact read prefixes identify the true window almost digitally, and Ref/Alt identity comes from bracket order (the first allele is -the reference-genome base — verified at all 3,120 loci of this panel with +the reference-genome base, verified at all 3,120 loci of this panel with zero swaps). ```bash @@ -307,59 +320,62 @@ python3 madcats.py infer-design \ --output inferred_reference_tags.csv ``` -Two evidence tiers, strictly ordered: exact read-prefix votes decide first -and are authoritative; an identity-envelope fuzzy pass (seeded matching -within the same 80% identity rule as generation, with already-resolved tags -acting as competition sinks) runs only for loci with zero exact support and -can never overrule exact evidence. Each locus needs a dominant window -(default 10x the runner-up); the written anchor (`LeftPrimerSequence`) is the -shortest panel-unique tag prefix, since the true primer boundary is -unobservable in seamless reads and unnecessary for assignment. `--tag-length` -sets the panel's reported tag length (54, 81, 109, ...); reads must reach it -and the design flanks must contain a full window, both validated per locus. - -Measured blinded on this project (primer file untouched, ~11 minutes): -3,068/3,120 loci inferred — 2,742 by exact evidence (100.0% correct against -the primer-derived truth) and 326 by the fuzzy tier (319 correct, 97.9%); -zero Ref/Alt swaps or variant-position errors; 52 loci excluded with stated -reasons (no reads within identity, support below threshold, or ambiguous -windows). Running `generate` on the inferred panel reproduces 99.1% of the -full-input MADC's rows (novel Match/Other rows: 99.65%) with 100% -classification agreement; count totals run 0.6% high because the short -anchors reject fewer error-carrying reads than the truer, longer primers. +Inference uses two evidence tiers in strict order. Exact read-prefix votes +decide first and are authoritative. An identity-envelope fuzzy pass +(seeded matching within the same 80% identity rule as generation, with +already-resolved tags acting as competition sinks) runs only for loci +with zero exact support and can never overrule exact evidence. Each locus +needs a dominant window (default 10x the runner-up). The written anchor +(`LeftPrimerSequence`) is the shortest panel-unique tag prefix, since +the reads do not show the true primer boundary and assignment does not +need it. `--tag-length` +sets the panel's reported tag length (54, 81, 109, ...). Reads must reach it +and the design flanks must contain a full window, and inference checks +both per locus. + +In a blinded run on this project (primer file untouched, ~11 minutes), +inference resolved 3,068/3,120 loci, 2,742 by exact evidence (100.0% +correct against the primer-derived truth) and 326 by the fuzzy tier (319 +correct, 97.9%). It made zero Ref/Alt swaps or variant-position errors +and excluded 52 loci with stated reasons (no reads within identity, +support below threshold, or ambiguous windows). Running `generate` on +the inferred panel reproduces 99.1% of the full-input MADC's rows (novel +Match/Other rows 99.65%) with 100% classification agreement. Count totals +run 0.6% high because the short anchors reject fewer error-carrying reads +than the truer, longer primers. The `*.qc.json` report records each locus's route, support, margin, anchor -length, and flags. The fuzzy tier is the review tier: its errors win by +length, and flags. The fuzzy tier is the review tier. Its errors win by large margins (paralog haplotype pools), so no internal statistic can catch -them — cross-check `fuzzy_anchor` loci against any delivered MADC's +them. Cross-check `fuzzy_anchor` loci against any delivered MADC's canonical rows or a public panel asset, and prefer those sources outright when available (a single delivered MADC reconstructs the panel exactly). -Inference is a one-time operation per panel; freeze its CSV and reuse it. +Inference is a one-time operation per panel, so freeze its CSV and reuse it. `scripts/validate_inferred_design.py` compares an inferred panel against a ground-truth reference-tag CSV, with per-route accuracy breakdowns. ## Migration from 0.4.x -Version 0.5.0 changed the discovery semantics, so the evidence flags were -renamed to make old commands fail loudly rather than silently change meaning: +Version 0.5.0 changed the discovery semantics and renamed the evidence +flags so that old commands fail loudly rather than silently change meaning: - `--min-quality-support` became `--quality-min-clean-reads` (and the route - is now optional and off by default); + is now optional and off by default). - `--novel-min-reads-per-sample`/`--novel-min-samples` became `--reproducible-min-reads`/`--reproducible-min-samples`, and the reproducibility test moved from a post-hoc AND filter into the core - evidence rule (routes combine by OR); -- `--depth-min-reads` is new; -- `--allele-catalogue`/`--known-only` were removed: fixed allele-ID + evidence rule (routes combine by OR). +- `--depth-min-reads` is new. +- `--allele-catalogue`/`--known-only` are gone, because fixed allele-ID assignment and the cross-project allele database are downstream HapApp responsibilities, and reprocessing against a frozen catalogue is no longer - this pipeline's job; -- the per-sample cache format version rose to 0.4.0 (fuzzy primer matches now + this pipeline's job. +- The per-sample cache format version rose to 0.4.0 (fuzzy primer matches now resolve across all matched depths by tag identity instead of preferring the - deepest primer), so caches are rebuilt on first use. Rebuilding is cheap: - assignment decisions are memoized per unique sequence, which made - per-sample processing 7.1x faster; the full 80-sample, 154.6M-read project - processes from scratch in about 4.5 minutes with 8 workers and regenerates - from a warm cache in about a minute. + deepest primer), so caches rebuild on first use. Rebuilding is cheap + because the pipeline memoizes assignment decisions per unique sequence, + which made per-sample processing 7.1x faster. The full 80-sample, + 154.6M-read project processes from scratch in about 4.5 minutes with 8 + workers and regenerates from a warm cache in about a minute. ## Validation on the supplied project @@ -379,80 +395,81 @@ are exactly equal, and the shared count total is 2.0% above DArT's. ### Why the evidence model changed -The 0.4.x discovery gate required project-wide reads whose **every** tag base +The 0.4.x discovery gate required project-wide reads whose every tag base reaches Q20. Auditing the raw caches showed this vetoed 286 vendor rows that -are present as exact 81-bp FASTQ prefixes with strong support — up to 6,626 -reads spread across as many as 70 samples — because one base position is -systematically low-quality (for many, below Q10, so no clean-read threshold -can rescue them). Symmetrically, the old `10x4` post-filter removed 598 -vendor rows that had clean-read support but narrower sample spread. The -reproducibility-primary rule recovers both classes; every vetoed-but- -reproducible vendor row is present in the 0.5.0 default output. +are present as exact 81-bp FASTQ prefixes with strong support, up to 6,626 +reads spread across as many as 70 samples, because one base position is +systematically low-quality (for many, below Q10, so no clean-read +threshold can rescue them). Symmetrically, the old `10x4` post-filter +removed 598 vendor rows that had clean-read support but narrower sample +spread. The reproducibility-primary rule recovers both classes, and every +vetoed-but-reproducible vendor row is present in the 0.5.0 default output. The vendor's own file shows DArT applies no within-project support threshold -of this kind: 27.3% of its positive-count rows have fewer than 10 reads in +of this kind. Of its positive-count rows, 27.3% have fewer than 10 reads in fewer than 2 samples of its own counts, 4,081 rows have under 10 total reads, and 1,417 rows are all-zero. Its row list reflects proprietary clustering -plus a cross-project haplotype database — reproducibility evidence at the -database level, which a single-project de novo run cannot see. The +plus a cross-project haplotype database, which supplies reproducibility +evidence at the database level that a single-project de novo run cannot see. The within-project evidence rule is therefore this pipeline's explicit, configurable substitute, not an imitation of a vendor threshold. ### Independent validation: red clover (diploid, 109-bp tags, low depth) -The DCl25-10856 red clover project (376 samples, 3,000 loci, 109-bp tags, -mean read length ~88 bp so only ~65% of reads reach the tag length, ~60x mean -locus depth) was processed with no primer file: the probe-design targets plus -`infer-design` recovered 2,968 loci — 2,902 exactly matching the vendor's -canonical tags, 56 differing only by the vendor's IUPAC curation, and the -remaining handful confined to loci where the vendor's own tags have zero -reads. `scripts/madc_to_reference_tags.py` converted the delivered MADC into -the equivalent panel (3,000/3,000) as the cross-check route. +MADCATS processed the DCl25-10856 red clover project (376 samples, 3,000 +loci, 109-bp tags, mean read length ~88 bp so only ~65% of reads reach the +tag length, ~60x mean locus depth) with no primer file. The probe-design +targets plus `infer-design` recovered 2,968 loci. Of these, 2,902 match the +vendor's canonical tags exactly, 56 differ only by the vendor's IUPAC +curation, and the remaining handful sit at loci where the vendor's own +tags have zero reads. `scripts/madc_to_reference_tags.py` converted the +delivered MADC into the equivalent panel (3,000/3,000) as the +cross-check route. Generation at the defaults gave 85.4% precision and 62.9% raw recall with -100% classification agreement and a 0.9975 shared-count total ratio. The raw -recall is dominated by a structural ceiling: 36.7% of the vendor's -positive-count rows fail every within-project evidence route on the vendor's -own counts (their cross-project catalogue at low depth); against +100% classification agreement and a 0.9975 shared-count total ratio. A +structural ceiling dominates the raw recall. Of the vendor's +positive-count rows, 36.7% fail every within-project evidence route on +the vendor's own counts (their cross-project catalogue at low depth). Against evidence-bearing vendor rows, recall is 94.1%. Softening to `--reproducible-min-reads 5 --depth-min-reads 15` captured nearly the whole recoverable band (67.2% recall against a 67.0% ceiling) at a 10-point -precision cost — but carrier-frequency profiling shows why the bare soft -view is not recommended: its vendor-shared additions look like real alleles +precision cost. Carrier-frequency profiling shows why the bare soft +view is not recommended. Its vendor-shared additions look like real alleles (median 44% of their carrier's locus reads, matching the 48% of established -rows), while its generated-only additions sit at a median 7.5% — not a -diploid genotype. The defaults remain the recommendation for diploid and +rows), while its generated-only additions sit at a median 7.5%, which is +not a diploid genotype. The defaults remain the recommendation for diploid and polyploid projects alike. When a low-depth diploid project needs more -sensitivity, add the diploid-justified frequency floor: +sensitivity, add the diploid-justified frequency floor. With it, `--reproducible-min-reads 5 --depth-min-reads 15 --min-supporting-freq 0.10` recovers about 40% of the available recall band while excluding the -artifact-profile rows, and its extra rows should still be confirmed by -segregation or replicates downstream. On this project the pre-0.10 partial +artifact-profile rows, and segregation or replicates should still confirm +its extra rows downstream. On this project the pre-0.10 partial salvage (minimum length 30, no locus guard) added the ~24M primer-bearing short reads to counts without changing the row set, and lowered count concordance with the vendor (Pearson 0.976 to 0.941), showing the vendor -does not count short fragments; the 0.10.0 default (minimum length +does not count short fragments. The 0.10.0 default (minimum length `--tag-length` minus 9) excludes those fragments, and `--partial-read-mode off` restores the exact pre-salvage counts when vendor comparability matters. Segregation-based validation closed the loop on this project. The run contains a 152-progeny bi-parental mapping family with both parents, and -both MADCs were pushed through the same updog (diploid) + BIGr workflow. +both MADCs went through the same updog (diploid) + BIGr workflow. Updog imputes dosages at low or zero depth (about a third of calls sit at DP=0), so all comparisons are depth-filtered. Dosage concordance between the two pipelines' calls is 99.73% at DP>=10 in both (99.77% at DP>=20). -Mendelian-violation rates in the family are statistically identical — +Mendelian-violation rates in the family are statistically identical, at 3.38% for this pipeline versus 3.35% for the vendor MADC (parents DP>=20, -progeny DP>=10, MPP>=0.9) — so the shared violation floor reflects the +progeny DP>=10, MPP>=0.9), so the shared violation floor reflects the assay and family, not either counting implementation. Family transmission of microhaplotype rows (present at >=5 reads in >=2 progeny must appear in -a parent) adjudicates the discovery tiers directly: vendor-shared novel -rows are parent-confirmed at 97.4% (the assay background), the default -configuration's generated-only rows at 72.0% — majority genuinely -transmitted alleles absent from the vendor's catalogue — and the soft -band's generated-only rows at only 28.4%, independently confirming the -carrier-frequency verdict that the bare soft view admits mostly artifacts. -The symmetric test on the vendor's own counts completes the picture: only +a parent) adjudicates the discovery tiers directly. Parents confirm +vendor-shared novel rows at 97.4% (the assay background), the default +configuration's generated-only rows at 72.0% (mostly transmitted alleles +absent from the vendor's catalogue), and the soft band's generated-only +rows at only 28.4%. That independently confirms the carrier-frequency +verdict that the bare soft view admits mostly artifacts. +The symmetric test on the vendor's own counts completes the picture. Only 313 of their 10,175 exclusive novel rows segregate in the family at all (the rest are read-starved catalogue content this project can neither validate nor falsify), and those confirm at 67.7% against a 97.8% @@ -460,12 +477,12 @@ consensus background on the same count matrix. Each pipeline's exclusive rows therefore carry the same real-but-imperfect profile (72.0% versus 67.7%, indistinguishable at n=313), while this pipeline contributes about three times as many transmission-validated alleles (~633) as it forgoes -(~212) — and the forgone ones sit in known, tunable territory just below -the evidence thresholds. +(~212), and the forgone ones sit in known, tunable territory immediately +below the evidence thresholds. -The canonical Ref/Alt rows — the input to downstream dosage calling — -compare to the vendor's as follows. Of our 5,936 canonical rows, 5,827 -(98.2%) are sequence-identical to the vendor's; the 109 differences are 89 +The canonical Ref/Alt rows, which are the input to downstream dosage +calling, compare to the vendor's as follows. Of our 5,936 canonical rows, 5,827 +(98.2%) are sequence-identical to the vendor's. The 109 differences are 89 vendor-IUPAC-curated sequences plus the Ref/Alt pairs of the 10 loci whose vendor tags carry zero reads in this project. Across the 2.19 million matched count cells, Pearson correlation is 0.975 with a mean absolute @@ -474,86 +491,87 @@ Ref/(Ref+Alt) ratio, evaluated over the 499,414 locus-by-sample cells where both files have at least 20 reads of canonical depth, the median ratio difference is 0.0000 (95th percentile 0.015) and 99.68% of cells imply the identical naive diploid genotype class. The zero-count canonical structure -also mirrors the vendor's (644 all-zero rows versus their 604) — the -germplasm-divergent loci both pipelines observe. +also mirrors the vendor's (644 all-zero rows versus their 604), reflecting +the germplasm-divergent loci both pipelines observe. ### Independent validation: blackberry (mixed ploidy, 109-bp tags, indels, degenerate primers) The DBla25-10927 blackberry project (376 samples of mixed *Rubus* species and ploidies, 3,015 loci, 109-bp tags, ~59-70% of reads reaching tag length) is the panel that motivated version 0.7.0's indel support and is -the first project validated through **all three panel-definition routes**. -Its design contains 10 indel markers — encoded with anchored VCF-style +the first project validated through all three panel-definition routes. +Its design contains 10 indel markers, encoded with anchored VCF-style brackets in the probe-design file but unanchored dash notation in the -primer CSV — and, as the data revealed, primers synthesized with +primer CSV. As the data revealed, it also has primers synthesized with degenerate IUPAC bases over flanking SNPs, whose oligo sequence the -vendor's tags carry verbatim. DArT's delivered sample names were -misassigned for this project (a correction crosswalk exists); this -pipeline's targetid-named columns are immune to that class of error. +vendor's tags carry verbatim. DArT misassigned the delivered sample names +for this project (a correction crosswalk exists), but this pipeline's +targetid-named columns are immune to that class of error. Version 0.7.0 replaced the SNP-only window construction with one general -rule — the divergence point of a tag pair is the shared prefix of the two -full allele expansions — which handles SNPs, insertions, deletions, +rule, that the divergence point of a tag pair is the shared prefix of the +two full allele expansions. The rule handles SNPs, insertions, deletions, anchored brackets, and homopolymer shifts identically, and reconstructs tags as primer-sequence overlay plus genomic suffix so degenerate oligo bases persist. SNP-panel outputs are byte-identical through the change. Route-by-route results against the vendor's canonical tags: -- **Design route**: 2,881/3,015 exact; all 134 differences are vendor-IUPAC - loci; zero unexplained. All 10 indel loci reconstruct exactly, including - divergence positions shifted past homopolymer runs. -- **Bootstrap route**: exact by construction (3,015/3,015 converted, none - skipped, indels included). Generation from this panel: 92.9% precision, - 73.7% raw recall against a 75.7% within-project evidence ceiling (23.7% - of the vendor's positive rows carry no such evidence on their own - counts), **94.7% fair recall** — the third project inside the 94-95% - band — with 100% canonical row recovery, Pearson 0.981, and 99.2% - classification agreement (557 of the 639 disagreements sit at - IUPAC-canonical loci and 68 at indel loci, where the positional variant - heuristic and vendor curation legitimately differ). Family transmission - in the reciprocal Columbia Star x Kotata families (both parents - sequenced, 92 progeny) reproduces the red clover profile: - vendor-shared novel rows 98.5% parent-confirmed (n=12,064), - generated-only rows 74.0% (n=2,027); the test asserts only that progeny - alleles exist in a parent, so unknown hexaploid inheritance and - segmental allopolyploidy do not affect it. -- **Primer-free inference**: 2,943/3,015 loci inferred (72 excluded with - stated reasons); 2,796 exact plus 126 concrete realizations of - vendor-IUPAC tags — identical under IUPAC compatibility, the +- **Design route.** 2,881/3,015 tags are exact, all 134 differences are + vendor-IUPAC loci, and none is unexplained. All 10 indel loci + reconstruct exactly, including divergence positions shifted past + homopolymer runs. +- **Bootstrap route.** The tags are exact by construction (3,015/3,015 + converted, none skipped, indels included). Generation from this panel + gives 92.9% precision, 73.7% raw recall against a 75.7% within-project + evidence ceiling (23.7% of the vendor's positive rows carry no such + evidence on their own counts), and 94.7% fair recall, the third project + inside the 94-95% band. It also gives 100% canonical row recovery, + Pearson 0.981, and 99.2% classification agreement (557 of the 639 + disagreements sit at IUPAC-canonical loci and 68 at indel loci, where + the positional variant heuristic and vendor curation legitimately + differ). Family transmission in the reciprocal Columbia Star x Kotata + families (both parents sequenced, 92 progeny) reproduces the red clover + profile, with vendor-shared novel rows 98.5% parent-confirmed + (n=12,064) and generated-only rows 74.0% (n=2,027). The test asserts + only that progeny alleles exist in a parent, so unknown hexaploid + inheritance and segmental allopolyploidy do not affect it. +- **Primer-free inference.** Inference resolved 2,943/3,015 loci and + excluded 72 with stated reasons. It found 2,796 exact tags, 126 concrete + realizations of vendor-IUPAC tags, and 18 wrong windows (0.6%). The + realizations are identical under IUPAC compatibility, the information-theoretic limit when the oligo's degeneracy is unknowable - without the primer file — and 18 wrong windows (0.6%). Of the 10 indel - loci, 9 resolve exactly by read votes (one via the fuzzy tier at a locus - whose canonicals carry no reads) and 1 is excluded as ambiguous rather - than guessed. - -The 18 wrong windows decompose into three classes, none an inference -defect in read-bearing data: 8 are read-starved loci anchored on scraps; -2 are short-amplicon loci (72-bp and 105-bp amplicons, real reads that -never reach tag length); and ~8 are loci where the vendor counted + without the primer file. Of the 10 indel loci, 9 resolve exactly by + read votes (one via the fuzzy tier at a locus whose canonicals carry no + reads), and inference excludes 1 as ambiguous rather than guessing it. + +The 18 wrong windows fall into three classes, none an inference +defect in read-bearing data. Of these, 8 are read-starved loci anchored +on scraps, 2 are short-amplicon loci (72-bp and 105-bp amplicons, real +reads that never reach tag length), and ~8 are loci where the vendor counted thousands of reads for tags occurring zero times in the delivered FASTQs in any form. The leading explanation for the last class is the vendor's pre-delivery overrepresented-read filtering (quantified for sweetpotato -above): dominant amplicons are precisely what such a filter removes, the +above). Dominant amplicons are precisely what such a filter removes, the vendor counts predate it, and the affected loci are then unknowable to any FASTQ-based pipeline. -A germplasm note from the same run: the project's two "Marion" samples -are genetically different individuals (canonical-count correlation 0.47 -where technical replicates approach 1); one is near-clonal with the -"Newberry" sample (r=0.958) and the other matches nothing in the panel — -a plate-provenance question for curation, caught by targetid-level -fingerprinting. +The same run raised a germplasm question. The project's two "Marion" +samples are genetically different individuals (canonical-count +correlation 0.47 where technical replicates approach 1). One is +near-clonal with the "Newberry" sample (r=0.958) and the other matches +nothing in the panel. Targetid-level fingerprinting caught this +plate-provenance question for curation. ### AgriSeq (Ion Torrent) pathway: honeybee validation -AgriSeq reads violate the primer-started model three ways: amplicons are -sequenced from both ends (~50/50 orientation split), primer digestion and -primers placed outside the submitted targets disperse read starts, and Ion -Torrent's dominant error is the homopolymer indel (a median 24% of reads -per marker carry one across ~100 bp on the honeybee run, up to 77% at -run-rich loci — the rate climbs monotonically with the longest run in the -window). The pathway is two commands: +AgriSeq reads violate the primer-started model in three ways. The platform +sequences amplicons from both ends (~50/50 orientation split), primer +digestion and primers placed outside the submitted targets disperse read +starts, and Ion Torrent's dominant error is the homopolymer indel (a +median 24% of reads per marker carry one across ~100 bp on the honeybee +run, up to 77% at run-rich loci, and the rate climbs monotonically with +the longest run in the window). The pathway is two commands: ```bash # first run of a panel: learn window placement from observed coverage @@ -571,153 +589,156 @@ madcats.py generate --fastq-dir normalized/ --fastq-glob "*.fastq" \ --output project_MADC.csv ``` -The 41-bp default window is measured, not assumed: sweeping 41/61/81 bp on +The 41-bp default window comes from a measurement. Sweeping 41/61/81 bp on the 81-marker honeybee validation (24.2M reads, 81 samples of mixed drone -and worker material) showed longer windows lose coverage and indel-free -reads faster than they add context — end-to-end read yield 64%/59%/44% and -genotype call rate 96.6%/93.9%/85.6% — with the 81-bp concordance uptick a -survivor artifact of scoring only the easiest cells. Data-driven window +and worker material) showed that longer windows lose coverage and +indel-free reads faster than they add context, with end-to-end read yield +64%/59%/44% and genotype call rate 96.6%/93.9%/85.6%. The 81-bp +concordance uptick is a survivor artifact of scoring only the easiest +cells. Data-driven window placement (per marker, from observed read coverage, keeping the variant out of the anchor) raised adapter yield from 66% to 85.5% of raw reads. Since 0.8.1, auto placement scores coverage minus a soft tandem-repeat penalty (`--str-penalty`, default 0.002 per repeat bp beyond 4, unit -sizes 1-3): the original homopolymer tiebreak provably never fired, +sizes 1-3). The original homopolymer tiebreak provably never fired, because real coverage fractions are never exactly tied, and it was blind to dinucleotide repeats entirely. Genotypes called from target-base dosage agree with the vendor's Torrent caller at 90.6%, and both pipelines agree with an independent pre-existing -reference genotype set at 94.4% versus 94.5% — a dead heat, with disputed -cells splitting 48:48 and the residual disagreement concentrated at a -handful of three-way-inconsistent markers — most of which the second-chip +reference genotype set at 94.4% versus 94.5%, a dead heat. Disputed +cells split 48:48, and the residual disagreement concentrates at a +handful of three-way-inconsistent markers, most of which the second-chip study below traced to window placement rather than to the loci -themselves. Row accuracy against the Amel_HAv3.1 genome: all 81 +themselves. For row accuracy against the Amel_HAv3.1 genome, all 81 real markers' Ref tags occur verbatim at their named coordinates and every -Alt tag is structurally exact; the only four failures are the vendor's +Alt tag is structurally exact. The only four failures are the vendor's four design-failed markers, whose submitted target sequences do not match -the genome at their named positions — a pre-submission target-versus- -genome check would have caught them before synthesis. Caveats: a single +the genome at their named positions. A pre-submission target-versus-genome +check would have caught them before synthesis. The caveats are a single project, two imperfect arbiters, and mixed-ploidy material, which the row-level checks tolerate by construction. ### Second chip, replicates, and window freezing (0.8.1) -A second honeybee chip on the same panel (96 wells: 65 unique samples, 30 -within-chip technical replicate pairs, one no-template control; 40.8M -reads at 2.5x the first chip's depth) ran the recipe unchanged: 84.8% of -raw reads normalized, the control clean at 119 reads against a -160,000-read median sample, vendor-caller concordance 92.4%, and — the -first truth-free accuracy instrument — 98.2% genotype concordance across -the 30 replicate pairs. The depth-scaling law reproduced exactly: -default evidence thresholds admitted 4,410 novel rows at this depth -(1,752 on chip 1), while `--min-supporting-freq 0.10` pinned the count -near 145 on both chips and improved every concordance metric, settling -the frequency floor as the AgriSeq default. +A second honeybee chip on the same panel (96 wells holding 65 unique +samples, 30 within-chip technical replicate pairs and one no-template +control, with 40.8M reads at 2.5x the first chip's depth) ran the recipe +unchanged. It normalized 84.8% of raw reads, its control held only 119 +reads against a 160,000-read median sample, and vendor-caller +concordance was 92.4%. The first truth-free accuracy instrument, genotype +concordance across the 30 replicate pairs, reached 98.2%. The +depth-scaling law reproduced. Default evidence thresholds admitted 4,410 +novel rows at this depth (1,752 on chip 1), while +`--min-supporting-freq 0.10` pinned the count near 145 on both chips and +improved every concordance metric, settling the frequency floor as the +AgriSeq default. The chips also exposed a stability failure with consequences for -microhaplotype databases: re-learning window placement per run moved 42 +microhaplotype databases. Re-learning window placement per run moved 42 of 85 windows, which made 58% of the second chip's haplotype sequences -spuriously "novel" against the first chip — technical artifacts +spuriously "novel" against the first chip. Those technical artifacts are indistinguishable from biology in any downstream database. Freezing the panel with `--reuse-tags` (the emitted window CSV is byte-identical to the source panel, every row validated against the design, partial mismatches refused) raised cross-chip haplotype sharing from 42% to 88%, -with the remainder consistent with genuinely new germplasm on the second -chip. +with the remainder consistent with new germplasm on the second chip. Window placement also turned out to be the dominant cause of apparently -bad markers, through allele-biased read dropout: where a variant allele +bad markers, through allele-biased read dropout. Where a variant allele extends an adjacent tandem repeat, its reads carry longer runs and die preferentially inside any window spanning the repeat, faking monomorphism. Surgical single-marker re-windowing rescued four of the five worst markers on both chips (9%->100%/96%, 27%->99%/96%, 48%->100%/99% vendor concordance), leaving only two markers plus one -sub-amplicon-spaced marker cluster genuinely bad on every window tried — -the true redesign list. The settled production workflow is: first chip -with penalized auto placement, patch the few coverage-forced windows the -cross-run comparison exposes, freeze the curated panel, and run every -subsequent chip with `--reuse-tags`. The curated frozen honeybee panel +sub-amplicon-spaced marker cluster bad on every window tried. Those form +the true redesign list. The settled production workflow is to run the +first chip with penalized auto placement, patch the few coverage-forced +windows the cross-run comparison exposes, freeze the curated panel, and +run every subsequent chip with `--reuse-tags`. The curated frozen honeybee panel scores 93.4%/93.9% vendor concordance on the two chips with 98.0% replicate concordance. Re-sweeping window sizes under the new scoring (31/41/61 bp, frequency floor on) confirmed 41 bp at the knee of the concordance-versus- -information curve: 31 bp genotypes marginally better (92.7% vs 91.8%) -but carries 20% fewer distinct discovered microhaplotypes (110 vs 137), -while 61 bp adds essentially none (138) and loses two concordance points -— on this chemistry, indel exposure destroys the extra flanking -variation as fast as a longer window adds it. Curation matters more than -size: the curated 41-bp panel outscores every uncurated size. +information curve. At 31 bp, genotyping is marginally better (92.7% vs +91.8%) but the panel carries 20% fewer distinct discovered +microhaplotypes (110 vs 137), while 61 bp adds almost none (138) and +loses two concordance points. On this chemistry, indel exposure destroys +the extra flanking variation as fast as a longer window adds it. +Curation matters more than size. The curated 41-bp panel outscores every +uncurated size. ### External benchmarks on public datasets (GT-seq, rhAmpSeq) Public datasets extend the validation record beyond in-house data, with -intake converters archived beside each dataset (the Flex-Seq capture -benchmark is documented in the 0.9.0 section below). +intake converters archived beside each dataset (the 0.9.0 section below +documents the Flex-Seq capture benchmark). -**Pacific oyster AgriSeq** (PRJNA1118744; 372 Ion S5 samples, 591 +**Pacific oyster AgriSeq** (PRJNA1118744, 372 Ion S5 samples, 591 amplicons of median 170 bp, design published as Ion AmpliSeq Region + Hotspot BEDs converted against the oyster_v9 genome with zero REF -mismatches): with the honeybee-derived defaults unmodified, 88.4% of +mismatches). With the honeybee-derived defaults unmodified, 88.4% of 144.6M raw reads normalized and genotypes agreed with the vendor's -Torrent VariantCaller at **94.52%** (143,383/151,693 cells across 371 +Torrent VariantCaller at 94.52% (143,383/151,693 cells across 371 name-matched samples, depth >= 20), 97.85% on the 460/542 markers above -90% — within half a point of the curated in-house honeybee panel, on a -foreign lab, species, chip generation, and target length. One panel-size -effect appeared on schedule: 12-bp assignment anchors collide at 591 -markers (the birthday bound predicts it), resolved at the time with -`--anchor-length 13`. Since 0.8.3, normalize-reads assigns anchors per -locus instead (the same allocator infer-design uses): every marker keeps +90%. This result is within half a point of the curated in-house honeybee panel, +on a foreign lab, species, chip generation, and target length. One +panel-size effect appeared on schedule. Assignment anchors of 12 bp +collide at 591 markers (the birthday bound predicts it), which +`--anchor-length 13` resolved at the time. Since 0.8.3, normalize-reads +assigns anchors per locus instead (the same allocator infer-design uses). +Every marker keeps the `--anchor-length` minimum, only colliding prefix groups grow, and windows identical all the way to the variant share an anchor with a surfaced warning (their reads resolve by full-tag identity downstream). -A 17,500-marker genome-wide stress panel measured the necessity — 111 -colliding 12-mer groups, far above the random-sequence bound — and runs +A 17,500-marker genome-wide stress panel measured the necessity, with 111 +colliding 12-mer groups, far above the random-sequence bound. It runs in ~820 MB with 17,291 markers at the minimum and 209 grown to 13-32 bp. -**Delta smelt GT-seq** (Zenodo 10.5281/zenodo.19069550; 96 PE100 -samples, 410 loci, and — uniquely — the panel's real primer file): +**Delta smelt GT-seq** (Zenodo 10.5281/zenodo.19069550, 96 PE100 +samples, 410 loci, and, uniquely, the panel's real primer file). GT-seq R1 reads are primer-started, so this platform needs no normalize-reads stage and exercised the primer-informed `design` route on non-DArT data for the first time, unchanged. Genotypes from the R1-only MADC agreed with the archive's independent BWA/bcftools -reference VCF at **98.80%** (33,928/34,340 cells; 99.72% on the -well-behaved core; per-sample median 98.9% across all 96 samples) — the -pipeline's best platform result, on indel-free Illumina chemistry. The -same dataset settled the primer-free question: `infer-design`, run with -the primer file withheld, recovered **368/368 loci's Ref and Alt tags -exactly** as the physical primers define them — a 100% inference score +reference VCF at 98.80% (33,928/34,340 cells, 99.72% on the +well-behaved core, per-sample median 98.9% across all 96 samples). That +was the pipeline's best platform result, on indel-free Illumina +chemistry. The same dataset settled the primer-free question. With the +primer file withheld, `infer-design` recovered 368/368 loci's Ref and Alt +tags exactly as the physical primers define them, a 100% inference score against ground truth rather than a vendor report. -**Vitis rhAmpSeq** (PRJNA281110, Cornell; the published 2,000-marker -collinear-core panel, NextSeq PE150, 200-300-bp amplicons): the panel +**Vitis rhAmpSeq** (PRJNA281110, Cornell, the published 2,000-marker +collinear-core panel, NextSeq PE150, 200-300-bp amplicons). The panel was designed on the collinear core of multiple *Vitis* genomes, so many -markers have no exact home on any single reference — intake is -**reference-free**: each marker's target frame is the consensus of its +markers have no exact home on any single reference. Intake is therefore +reference-free, and each marker's target frame is the consensus of its own primer-anchored read pileup. An R1-only first pass recovered 1,405 -markers at 63% read assignment; the paired-end route then measured the -geometry (94.8% of pairs overlap and merge — the platform's own +markers at 63% read assignment. The paired-end route then measured the +geometry (94.8% of pairs overlap and merge, and the platform's own published pipeline merges with FLASH, independently confirming -merge-first) and rebuilt consensus from full merged amplicons: **1,759 -markers (+25%), frames of median 228 bp, up to three 110-bp tiles per -amplicon** (2,951 markers, 1,030 multi-SNP amplicons), 79.3% read +merge-first) and rebuilt consensus from full merged amplicons. That gave +1,759 markers (+25%), frames of median 228 bp, up to three 110-bp tiles +per amplicon (2,951 markers, 1,030 multi-SNP amplicons), and 79.3% read extraction with `covered` routing. The tiled windows capture ~90% of all segregating sites (production's full-insert haplotypes span ~174 bp -and capture all sites plus cross-tile phase; the trade buys fixed-length, -frozen, cross-run-comparable MADC haplotypes). The merger itself was -validated against FLASH 1.2.11, vsearch, and fastp on a four-regime -exact-truth pair set — equal to the best (vsearch) in every regime, -zero false merges, and on real NextSeq data the only inter-tool +and capture all sites plus cross-tile phase, and the trade buys +fixed-length, frozen, cross-run-comparable MADC haplotypes). Tests +against FLASH 1.2.11, vsearch, and fastp on a four-regime exact-truth +pair set put the merger equal to the best (vsearch) in every regime, +with zero false merges. On real NextSeq data the only inter-tool differences are equal-quality overlap ties, where a per-locus pileup jury rules our R1-preferring pick correct 62.6% of the time. No public genotype matrix exists for these accessions, but family -structure is its own truth: progeny of a biparental cross can carry at -most four haplotypes per locus (two per parent), each individual at -most two. All **eight biparental families in the submission (763 runs, -~17.5 GB) were processed family-by-family under a 56 GB disk budget** -against one frozen 2,951-window panel (`--reuse-tags`), so haplotypes -are identical objects across families: +structure is its own truth. Progeny of a biparental cross can carry at +most four haplotypes per locus (two per parent), and each individual at +most two. All eight biparental families in the submission (763 runs, +~17.5 GB) went through the pipeline family-by-family under a 56 GB disk +budget against one frozen 2,951-window panel (`--reuse-tags`), so +haplotypes are identical objects across families: | family | progeny | informative loci | <=4 family haps | <=2 per progeny | calls within inferred parental 4 | |---|---|---|---|---|---| @@ -729,54 +750,56 @@ are identical objects across families: (Three additional tiny families, n = 2-7, are consistent at 99.5-100%.) Across ~14,900 locus-family tests spanning eight independent crosses -and three sequencing batches, **99.92-99.99% of all haplotype calls in +and three sequencing batches, 99.92-99.99% of all haplotype calls in every family are alleles of that locus's four inferred parental -haplotypes** — at three nines, the microhaplotypes the MADC reports in +haplotypes. At three nines, the microhaplotypes the MADC reports in 763 offspring are the parental alleles Mendelian transmission requires. ### Read accounting -The QC JSON now reports where every read goes. For the default run: -154,584,628 FASTQ records; 88,126,464 assigned to a locus at full length; -87,373,009 (99.1% of assigned) retained in emitted rows; 753,455 dropped with -their 558,194 low-evidence sequences (mean 1.3 reads each); 3,294,541 moved -between sequences by within-sample denoising and 103,628 by cross-sample -denoising (moved reads stay in the table under their centroid). Per-sample +The QC JSON now reports where every read goes. The default run had +154,584,628 FASTQ records, of which the pipeline assigned 88,126,464 to a +locus at full length and retained 87,373,009 (99.1% of assigned) in +emitted rows. It dropped 753,455 with their 558,194 low-evidence +sequences (mean 1.3 reads each). Within-sample denoising moved 3,294,541 +between sequences and cross-sample denoising moved 103,628 (moved reads +stay in the table under their centroid). Per-sample `reads_in_emitted_rows` joins the existing per-sample QC. Twelve samples have -fewer than 100,000 assignable 81-bp tags (lowest: `4404075` with 23); these -FASTQs are dominated by short or primer-less reads and downstream -completeness should be reviewed for them. (Those figures are the 0.5.0 run; -since 0.10.0 the pooled pass folds same-allele sequences only — -`reads_moved_by_global_denoise` keeps its name — and the ledger gains +fewer than 100,000 assignable 81-bp tags (the lowest, `4404075`, has 23). +Short or primer-less reads dominate these FASTQs, so review their +downstream completeness. (Those figures are from the 0.5.0 run. Since +0.10.0 the pooled pass folds same-allele sequences only, though +`reads_moved_by_global_denoise` keeps its name, and the ledger gains `reads_assigned_gapped`, `reads_n_mapped` and `reads_n_dropped`.) ### Historical exploratory analyses (0.3.x) -The `results/v03_*` files document the audits that motivated the redesign: -characterization of generated-only rows, right-primer support, cross-extract -reproducibility of paired leaf/root samples, and a diagnostic BLAST against -the public NSP306 *I. trifida* reference following the open `dartag_alleles` -pattern (best hit at the designed locus for most high-support extra rows; -off-target best hits flagged for paralog review, without automatic exclusion -because cultivated sweetpotato is hexaploid and the reference is diploid). -Those analyses used the 0.3.x quality-gated outputs; their row lists are -superseded by the evidence model above, but the biological conclusions — -filter the low-support tail, keep reproducible on-target microhaplotypes, -flag multimappers — are what the current defaults implement. +The `results/v03_*` files document the audits that motivated the redesign, +covering characterization of generated-only rows, right-primer support, +cross-extract reproducibility of paired leaf/root samples, and a +diagnostic BLAST against the public NSP306 *I. trifida* reference +following the open `dartag_alleles` pattern (best hit at the designed +locus for most high-support extra rows, and off-target best hits flagged +for paralog review, without automatic exclusion because cultivated +sweetpotato is hexaploid and the reference is diploid). +Those analyses used the 0.3.x quality-gated outputs. The evidence model +above supersedes their row lists, but the current defaults implement +their biological conclusions, which are to filter the low-support tail, +keep reproducible on-target microhaplotypes, and flag multimappers. ### Evidence about prior FASTQ filtering and tag length -Every vendor `AlleleSequence` and `ClusterConsensusSequence` is exactly 81 -bp; the panel design reconstructs a 97-bp primer-to-primer amplicon at all +Every vendor `AlleleSequence` and `ClusterConsensusSequence` is 81 +bp long. The panel design reconstructs a 97-bp primer-to-primer amplicon at all 3,120 loci, so an 81-bp tag is an observed prefix of a longer amplicon. The two target manifests report 175,642,223 `tagcounttotal` observations versus -154,584,628 delivered FASTQ records; applying each manifest's `overreppct` +154,584,628 delivered FASTQ records. Applying each manifest's `overreppct` predicts 18,989,753 removed overrepresented reads, and per-sample predicted -and observed deficits are strongly correlated. The delivered FASTQs were -therefore already filtered before release, which supports the preprocessing +and observed deficits are strongly correlated. The vendor therefore +filtered the delivered FASTQs before release, which supports the preprocessing hypothesis without identifying the exact vendor commands. A raw-data audit finds 17,334 of the vendor's 18,677 pure-ACGT rows as exact 81-bp FASTQ -prefixes; the vendor also reports 569 Ref/Alt rows with curated IUPAC +prefixes. The vendor also reports 569 Ref/Alt rows with curated IUPAC ambiguity (their concrete groupings are not derivable from the A/C/G/T probe design) and 73 Match/Other rows containing `N`. All 6,238 81-bp prefixes of the public Breeding Insight PanelHub 109-bp design sequences agree exactly @@ -787,112 +810,112 @@ with this pipeline's independently reconstructed tags. Statistics columns the pipeline does not compute (`OneRatioRef` through `AvgPIC`, and `RatioAvgCountRefAvgCountSnp`) emit `.` rather than a blank cell in every data row (with `--annotations on`, the default, `PICSnp` and -`AvgPIC` instead carry the `Variants` and `MarkerType` annotations — see -the 0.10.0 section). This is a 0.8.2 format change: byte comparisons -against MADCs generated by earlier versions will differ in exactly those -nine columns and nothing else. +`AvgPIC` instead carry the `Variants` and `MarkerType` annotations +described in the 0.10.0 section). This is a 0.8.2 format change, so byte +comparisons against MADCs from earlier versions will differ in those +nine columns only. Three `generate` flags reproduce the raw-MADC framing that preamble-expecting consumers such as HapApp and HapApp_utils rely on: - `--dart-preamble` prepends the vendor-style seven starred rows above the - header: service/project label, plate barcode, plate number, plate row, - plate column, plate name, and the targetid row, which carries the - FASTQ-derived sample ids directly above the header row's sample names — - the same fastq-id-over-sample-name adjacency as vendor files. Every - preamble cell without a value is `*`, exactly as in vendor output, with - one exception: the file's very first cell holds a full provenance string + header. They are the service/project label, plate barcode, plate number, + plate row, plate column, plate name, and the targetid row, which carries + the FASTQ-derived sample ids directly above the header row's sample + names, the same fastq-id-over-sample-name adjacency as vendor files. + Every preamble cell without a value is `*`, as in vendor output, with + one exception. The file's very first cell holds a full provenance string (pipeline, version, and every generation parameter as `key=value`, prefixed with `* ` so consumers that skip preamble lines by their leading star still skip it), so the file records how it was made even - when separated from its QC sidecar. No timestamp is included — output - stays byte-reproducible. + when separated from its QC sidecar. The preamble includes no timestamp, + so output stays byte-reproducible. - `--preamble-project` sets the label repeated across the first preamble - row's sample cells (default: the output filename before its first dot). + row's sample cells (by default the output filename before its first dot). - `--sample-lookup` takes a two-column CSV/TSV (FASTQ-derived sample id, - desired sample name; a header line is detected and skipped) and replaces + desired sample name, with any header line detected and skipped) and replaces the output column names while the targetid row keeps the FASTQ ids. Validation is deliberately strict, because a rename table with holes - silently mislabels count columns: every run sample must be mapped, ids - matching no sample are errors, and duplicate names are errors. + silently mislabels count columns. The table must map every run sample, + ids matching no sample are errors, and duplicate names are errors. -`read_madc` round-trips preambled output: the header is found by its -`AlleleID` cell, and a numeric, unique targetid row is adopted for sample -identity exactly as when reading vendor files. +`read_madc` round-trips preambled output. It finds the header by its +`AlleleID` cell and adopts a numeric, unique targetid row for sample +identity, as when reading vendor files. ## Paired-end reads and multi-window tiling (0.9.0) The single-window model reads one excised window per locus, which caps -usable data whenever the sequenced fragment is larger than one read: on +usable data whenever the sequenced fragment is larger than one read. On a dual-probe capture platform (Flex-Seq, ~300-bp probe-to-probe fragments, NovaSeq 2x150) only ~52% of reads could ever overlap the one window, by geometry rather than by quality. 0.9.0 adds the two missing -pieces — paired-end intake and multiple windows per locus — as explicit, +pieces, paired-end intake and multiple windows per locus, as explicit, separately validated mechanisms. **Paired-end intake is one explicit decision, never auto-detected.** Measured read geometry decides it: - **Overlapping pairs** (insert shorter than R1+R2, e.g. GT-seq PE100 - over 130-200-bp amplicons): merge first with the `merge-pairs` + over 130-200-bp amplicons). Merge first with the `merge-pairs` subcommand, then feed merged fragments to `normalize-reads` or `generate`. The merger reverse-complements R2, scans overlaps longest - first, and handles both geometries — the merged read is always R1's - head plus the overlap plus R2's tail, so in the extended geometry that - is the whole fragment, and in engulfed read-through R1's adapter tail - past the fragment end falls outside the overlap and is discarded by - construction (no adapter trimming step) while R2 bases past R1's end - are kept when the reads differ in length; disagreeing overlap bases - take the higher-quality call, `--unmerged r1|pool|drop` states what - happens to the remainder, mates are paired by read ID (out-of-step - names or unequal counts are a hard error), and samples are independent - so `--jobs` merges them in parallel processes. On a synthetic paired-end truth set with modeled - adapter read-through, 100% of 513,715 pairs merged and molecular count - recovery was 98.6% — one fragment, one count. -- **Non-overlapping dual-anchored designs** (Flex-Seq: R1s anchor the - left probe, R2s the right, mates cover opposite halves of a fragment - neither read spans): pool both mates as independent reads. Merging is - geometrically impossible there and pooling cannot double-count a - window, because no window is covered by both mates. - -**Multi-window tiling** puts several markers on one physical locus: an + first, and handles both geometries. The merged read is always R1's + head plus the overlap plus R2's tail. In the extended geometry this + covers the whole fragment. In engulfed read-through, R1's adapter tail past + the fragment end falls outside the overlap and drops out by + construction (no adapter trimming step), while the merger keeps R2 + bases past R1's end when the reads differ in length. Disagreeing + overlap bases take the higher-quality call, `--unmerged r1|pool|drop` + states what happens to the remainder, the merger pairs mates by read + ID (out-of-step names or unequal counts are a hard error), and samples + are independent, so `--jobs` merges them in parallel processes. On a + synthetic paired-end truth set with modeled adapter read-through, 100% + of 513,715 pairs merged and molecular count recovery was 98.6%, so each + fragment gave one count. +- **Non-overlapping dual-anchored designs** (Flex-Seq, where R1s anchor + the left probe, R2s the right, and mates cover opposite halves of a + fragment neither read spans). Pool both mates as independent reads. + Merging is geometrically impossible there and pooling cannot + double-count a window, because the two mates never cover the same + window. + +**Multi-window tiling** puts several markers on one physical locus. An optional `LocusGroup` column (probe-design TSV and reference-tags CSV) declares markers as tiles of one target region. Tiles must share an identical Ref expansion frame (validated at load), share one k-mer territory, and reads locate to the group before routing to member -windows. Panels without the column behave exactly as before, to the -byte. +windows. Panels without the column behave as before, to the byte. **Routing between a group's windows** is `--group-routing`: -- `nearest` (default): each read feeds exactly one tile — the fully +- `nearest` (default) feeds each read to a single tile, the fully covered window whose center is nearest the read's center. -- `covered`: the read's excision is emitted at every member window it +- `covered` emits the read's excision at every member window it fully covers. Each window still sees each fragment at most once in - both modes; the QC separates the extra per-window emissions + both modes, and the QC separates the extra per-window emissions (`tile_extra_emissions`) from the read-fate accounting. The distinction matters because merged full-span fragments all share -the amplicon's center, so `nearest` degenerates to winner-take-all: on -the GT-seq benchmark, one tile took effectively all depth at 163 of 164 +the amplicon's center, so `nearest` degenerates to winner-take-all. On +the GT-seq benchmark, one tile took almost all depth at 163 of 164 tiled loci and the other went dark. Use `covered` whenever reads span more than one tile (merged fragments, or long reads over closely spaced -tiles); a fragment that covers two windows genuinely observes both -SNPs. +tiles), because a fragment that covers two windows observes both SNPs. **Distinct-window guard.** Tiles share a coverage profile, so fresh -window placement can collapse two members onto the same start — and two +window placement can collapse two members onto the same start, and two markers with identical Ref tags make every ref-carrying read an exact -tie, which the assignment layer drops as ambiguous. Measured on GT-seq, +tie, which the assignment layer drops as ambiguous. On GT-seq, that silently zeroed a locus's ref depth and flipped its calls from 100% to 3% concordance. Fresh placement therefore forces member windows to excise distinct sequences (a colliding member takes its best-ranked -distinct start; the nudge is listed in QC `locus_groups.window_dedup_nudged`; -no distinct start at all is an error), and `--reuse-tags` refuses a +distinct start, QC lists the nudge in `locus_groups.window_dedup_nudged`, +and no distinct start at all is an error), and `--reuse-tags` refuses a frozen panel containing twin windows instead of replaying the defect. -**Window freezing is load-bearing for paired-end modes.** A four-way -GT-seq experiment on identical reads and truth (96 samples, 409 +**Paired-end modes depend on window freezing.** A four-way GT-seq +experiment ran on identical reads and truth (96 samples, 409 original + 206 added tile/rescued markers, DP >= 20 against the archive's independent BWA/bcftools VCF): @@ -901,52 +924,52 @@ archive's independent BWA/bcftools VCF): | R1-only | 98.80% | — | 34,340 | | pooled mates + fresh windows | 95.18% | 87.92% | — | | merged + fresh windows | 92.99% | 90.06% | — | -| merged + frozen tags + tiles, `covered` | **98.80%** | **98.43%** | **52,971** | +| merged + frozen tags + tiles, `covered` | 98.80% | 98.43% | 52,971 | Every fresh-placement regression was window drift (all 368 windows -moved; the worst landed on twin-window ambiguity), and the recipe that -holds is: `merge-pairs`, then `normalize-reads --reuse-tags` with the -proven panel plus tile rows, then `generate` — original markers +moved, and the worst landed on twin-window ambiguity). The recipe that +holds is `merge-pairs`, then `normalize-reads --reuse-tags` with the +proven panel plus tile rows, then `generate`. With it, original markers reproduce the R1-only result on the same cells while the tiles add 54% more truth-validated genotype calls at parity. On the dual-probe capture benchmark (cranberry Flex-Seq, 24 samples, 17,242 reconstructed clusters scored against the population truth VCF), -the same mechanisms lift the geometry ceiling: R1-only single-window -92.39% on 32,675 cells with median 7,733 loci recovered per sample; -pooling both mates raises it to 93.24% on 57,577 cells and 13,421 loci -(the published vendor pipeline recovered 14,550 of 17,502); a -three-tile 41,033-marker panel with `covered` routing reaches 82.9% -read extraction and **94.59% on 120,261 cells** — 3.7x the callable +the same mechanisms lift the geometry ceiling. R1-only single-window +calling scores 92.39% on 32,675 cells with median 7,733 loci recovered +per sample. Pooling both mates raises it to 93.24% on 57,577 cells and +13,421 loci (the published vendor pipeline recovered 14,550 of 17,502). +A three-tile 41,033-marker panel with `covered` routing reaches 82.9% +read extraction and 94.59% on 120,261 cells, 3.7x the callable genotypes of the single-window R1 run, at higher concordance. A subsequent full-cohort campaign (192 samples, K=4 tiles at 45-bp spacing with 110-bp windows, one cohort-level `generate`) raised capture of the population's segregating-site catalogue from 64.5% to -78.4% while *improving* trio incompatibility from 4.5% to 3.6% — -window geometry solved the coverage gap (outside-window misses fell -from 18.6% to 1.9% of sites) and cohort-scale evidence produced a -cleaner haplotype catalogue, not just a larger one. +78.4% while *improving* trio incompatibility from 4.5% to 3.6%. +Window geometry solved the coverage gap (outside-window misses fell +from 18.6% to 1.9% of sites), and cohort-scale evidence produced a more +accurate haplotype catalogue as well as a larger one. **Adapter trimming is not required, and adapter cannot reach the -emitted haplotypes.** Three structural guarantees, one per read mode: -windows are defined in frame coordinates and bounded by the frame -(`window start + length <= frame length`), so on amplicon platforms — -where the frame is the amplicon — a window cannot reach past the -biology into adapter by construction; merge mode removes read-through -adapter geometrically (the engulfed merge drops R1's tail past the overlap; -proven on the synthetic paired-end set with modeled read-through: 100% -merged, zero length errors); and pooled mode exists precisely for +emitted haplotypes.** There are three structural guarantees, one per +read mode. Windows live in frame coordinates and the frame bounds them +(`window start + length <= frame length`), so on amplicon platforms, +where the frame is the amplicon, a window cannot reach past the +biology into adapter by construction. Merge mode removes read-through +adapter geometrically (the engulfed merge drops R1's tail past the +overlap, and on the synthetic paired-end set with modeled read-through +it gave 100% merged and zero length errors). Pooled mode exists precisely for long-fragment designs whose reads end before the fragment does, so there is no read-through to leak. The residual theoretical path (capture platforms whose genome-slice frames outrun a short fragment, on the unmerged tail) funnels into identity-gate rejection, because variable shear junctions never reproduce as one sequence. The census -agrees: across 127,667 emitted rows in six MADCs spanning five +agrees. Across 127,667 emitted rows in six MADCs spanning five platforms (GT-seq at two window lengths, rhAmpSeq pooled and family-scale, the 41K-tile capture panel, Ion AgriSeq), zero rows contain TruSeq or Ion P1 adapter at a strict 13-mer probe. (A loose 10-mer probe flags one capture locus whose genome happens to contain -`AGATCGGAAG` diverging from TruSeq at base 11 — a chance genomic +`AGATCGGAAG` diverging from TruSeq at base 11. It is a chance genomic k-mer inside the reference tag itself, not contamination.) Measured on the capture benchmark, trimming adapters before the run changed dosage concordance by 0.05 points (92.24% untrimmed vs 92.19% trimmed) while @@ -954,350 +977,396 @@ costing 2 points of extraction from the shortened reads. ## Choosing the window length (`window-scan`) -Tag/window length was historically chosen per platform against external +Earlier versions chose tag/window length per platform against external truth (the honeybee 41-bp knee came from a concordance-versus-length sweep against vendor calls). `window-scan` makes the same decision from -the project's own reads: one coverage pass predicts **retention** +the project's own reads. One coverage pass predicts retention (fraction of located reads fully covering the best window) for a dense grid of lengths, and each candidate length then runs the real normalize-and-generate machinery on a sample subset to measure -**cleanliness** (assigned reads not absorbed by denoising or dropped as -failed evidence — per-base error and indel exposure accumulate with -length) and **information** (evidence-passing novel haplotype rows per -100 markers — rises with length until the local linked variation is -exhausted). The recommendation is **survival-first**: survival = -retention x assignment x cleanliness; candidates within `--info-band` +cleanliness (assigned reads not absorbed by denoising or dropped as +failed evidence, which falls as per-base error and indel exposure +accumulate with length) and information (evidence-passing novel +haplotype rows per 100 markers, which rises with length until the local +linked variation runs out). The recommendation is survival-first, where +survival = retention x assignment x cleanliness. Candidates within `--info-band` (default 10%) of the best survival are eligible, and the most informative eligible length wins, ties breaking short. Information -deliberately cannot lead the decision, because it can be inflated by -exactly the rows one fears: systematic errors (Ion homopolymer indel +deliberately cannot lead the decision, because the rows one fears can +inflate it. Systematic errors (Ion homopolymer indel families recur across samples) pass the reproducibility route and masquerade as haplotype diversity. An earlier score that weighted -information directly followed that inflation long — on Ion oyster data -it recommended 81 bp against the externally validated 41-bp knee — and -the survival-first rule was the correction. Output: a TSV of the -curves, a QC JSON, and per-length run directories; a candidate the -distinct-window guard refuses (tiles inseparable at that length) is -reported failed rather than aborting the sweep. +information directly followed that inflation long. On Ion oyster data +it recommended 81 bp against the externally validated 41-bp knee, and +the survival-first rule was the correction. The output is a TSV of the +curves, a QC JSON, and per-length run directories. The scan reports a +candidate the distinct-window guard refuses (tiles inseparable at that +length) as failed rather than aborting the sweep. Under the survival-first rule the scan reproduces every externally -arbitrated choice: Ion oyster 41 bp (assignment falls 15 points from -31 to 81 bp as indel-bearing reads fail the substitution-only identity -gate — the Ion damage shows in assignment, not cleanliness), GT-seq -81 bp (the frozen-validated length; the 96-sample truth test measured -110 bp at only -0.08 points, so the band's conservatism is cheap), and -capture 61 bp. On merged rhAmpSeq amplicons — clean chemistry, -fragments dwarfing every candidate, information unsaturated through -150 bp — the rule recommends 81 while the family instrument cleared -110 and the platform's own pipeline uses full inserts: where richer -haplotypes are the goal and an external or genetic arbiter is -available, widening `--info-band` expresses that choice explicitly. +arbitrated choice. It picks 41 bp for Ion oyster (assignment falls 15 +points from 31 to 81 bp as indel-bearing reads fail the substitution-only +identity gate, so the Ion damage shows in assignment rather than +cleanliness), 81 bp for GT-seq (the frozen-validated length, and the +96-sample truth test measured 110 bp at only -0.08 points, so the band's +conservatism is cheap), and 61 bp for capture. On merged rhAmpSeq +amplicons, with low-error chemistry, fragments dwarfing every candidate, +and information unsaturated through 150 bp, the rule recommends 81 while +the family instrument cleared 110 and the platform's own pipeline uses +full inserts. Where richer haplotypes are the goal and an external or +genetic arbiter is available, widening `--info-band` expresses that +choice explicitly. **Seed sensitivity (0.11.0).** The scan runs on a sample subset (six files by default), and a recommendation can be a property of that subset rather than of the panel. `--scan-draws N` repeats the whole sweep on N independent seeded draws (seeds `--scan-seed`, +1, +2, ...) into `draw_1/`, `draw_2/`, ... and reports each draw's recommendation, the -votes per length, and their agreement (`recommendation_stability`); -the consensus is the most-voted length, ties breaking short. A +votes per length, and their agreement (`recommendation_stability`). +The consensus is the most-voted length, ties breaking short. A recommendation that flips between draws is the signal to scan more -samples or to arbitrate externally — the one check a user without truth -can make on the length decision itself. +samples or to arbitrate externally. It is the one check a user without +truth can make on the length decision itself. -Falling cleanliness deserves a precise reading: a churned read is one +Falling cleanliness deserves a precise reading. A churned read is one whose exact sequence the denoiser recognized as an error neighbor and -folded back into its parent — the count survives, no error row is -emitted, so churn measures error-handling load, not leakage. The +folded back into its parent. The count survives and no error row +appears, so churn measures error-handling load, not leakage. The narrow leak path is a systematic error (same position, same substitution, recurring across samples) clearing the reproducibility -route and emitting as a false Match row — and the scan's information +route and emitting as a false Match row. The scan's information metric cannot distinguish that from real linked variation, so the scan is a screening instrument whose recommendation still wants an external -or genetic arbiter. On GT-seq the arbitration is done: the scan +or genetic arbiter. On GT-seq the arbitration is done. The scan recommended 110 bp over the historical 81, and against the archive's independent truth VCF on all 96 samples (identical merged reads, -identical fresh placement), 110 bp scores 98.62% versus 81 bp's 98.70% -— at most 0.08 points of dosage cost while emitting 27% more Match -haplotypes (1,568 vs 1,231 rows). The information the scan saw is not -corrupting target genotypes; whether each added Match row is linked -biology versus a systematic error family is exactly what the family -instrument settles (on rhAmpSeq at 110 bp: under 1% family-bound -violations across 763 progeny). The same experiment refined the -window-drift picture: fresh 81-bp placement WITH the distinct-window -guard scores 98.77/98.57 (old/new markers) versus the pre-guard 92.99/ -90.06 — the drift "catastrophe" was entirely the twin-window defect, -and honest residual drift costs only 0.03-0.14 points against frozen -windows. Freezing remains mandatory for cross-run haplotype identity; -it is no longer load-bearing for accuracy. +identical fresh placement), 110 bp scores 98.62% versus 81 bp's 98.70%. +The longer window costs at most 0.08 points of dosage while emitting 27% +more Match haplotypes (1,568 vs 1,231 rows). The information the scan saw is not +corrupting target genotypes. The family instrument settles whether each +added Match row is linked biology or a systematic error family (on +rhAmpSeq at 110 bp it found under 1% family-bound violations across 763 +progeny). The same experiment refined the window-drift picture. Fresh +81-bp placement WITH the distinct-window guard scores 98.77/98.57 +(old/new markers) versus the pre-guard 92.99/90.06, so the drift +"catastrophe" was entirely the twin-window defect, and the remaining +drift costs only 0.03-0.14 points against frozen windows. Freezing +remains mandatory for cross-run haplotype identity, but accuracy no +longer depends on it. ## General indel recovery and review fixes (0.10.0) Two independent code reviews and a colleague's finding on a DArTag project -— genome assemblies predicted indel-bearing microhaplotypes (1–13 bp, -often several events per tag) that the vendor MADC never reported, and -neither did 0.9.x — motivated this release. The 0.9.x identity gate was -substitution-only, so an undesigned indel frameshifts the tag against -every canonical sequence and the read was dropped as off-target; on that -project only 6 of 447 read-supported indel microhaplotypes fell inside the -envelope, while 423 lay within the same 20% budget once gaps count as -edits. +motivated this release. In that project, genome assemblies predicted +indel-bearing microhaplotypes (1–13 bp, often several events per tag) +that the vendor MADC never reported, and neither did 0.9.x. The 0.9.x +identity gate was substitution-only, so an undesigned indel frameshifts +the tag against every canonical sequence and the gate dropped the read as +off-target. On that project only 6 of 447 read-supported indel +microhaplotypes fell inside the envelope, while 423 lay within the same +20% budget once gaps count as edits. **One general mechanism, not a catalogue of cases.** When every primer -candidate rejects a read, `select_marker` offers one gapped reading: a +candidate rejects a read, `select_marker` offers one gapped reading. It is a start-anchored banded alignment (band = `--max-indel-length`, default 10) whose end may overhang by up to a band on either side (a read tail past the reference is a deletion's signature, a reference tail past the read an insertion's), scored under the same edit budget as substitutions. The -reading is believed only when it is composed like an indel haplotype — -at most 6 substitutions and 6 gap events alongside the gaps — because a +pipeline accepts the reading only when its composition is that of an +indel haplotype, with at most 6 substitutions and 6 gap events alongside +the gaps, because a co-amplified paralog reaches the budget through many substitutions (the captured reads on the motivating project carried a median of 13 substitutions per read against 2 for true indel haplotypes, and one locus -would otherwise have swollen from 351 to 38,653 reads). Accepted reads are -counted as ordinary fixed-length rows in the vendor's shifted-suffix -convention; the counting layer, evidence rules and denoiser are unchanged. +would otherwise have swollen from 351 to 38,653 reads). Accepted reads +count as ordinary fixed-length rows in the vendor's shifted-suffix +convention, and the counting layer, evidence rules and denoiser are unchanged. `classify_sequence` reads the target base at the position the *cheaper* -explanation puts it: the fixed offset unless a gapped reading is strictly -cheaper, well composed, and verified by at least 12 bases after its last -gap (clustered errors at a read end must not masquerade as a shift); a -target inside a deletion or pushed past the read is `Other`. This also -corrects in-envelope indel reads that 0.9.x classified at a shifted offset -— the delta smelt locus `NC_061083`, whose real 1-bp insertion scored 26% -against the truth VCF, is now concordant. Cost is bounded by an exact -lower bound: a Myers/Hyyrö bit-vector edit distance (C-speed integer -operations) proves most hopeless tags cannot meet the budget before any +explanation puts it. This position is the fixed offset unless a gapped +reading is strictly cheaper, well composed, and verified by at least 12 +bases after its last gap (clustered errors at a read end must not +masquerade as a shift). A target inside a deletion or pushed past the +read is `Other`. This also corrects in-envelope indel reads that 0.9.x +classified at a shifted offset. +The delta smelt locus `NC_061083`, whose real 1-bp insertion scored 26% +against the truth VCF, is now concordant. An exact lower bound limits the +cost. A Myers/Hyyrö bit-vector edit distance (C-speed integer +operations) proves that most hopeless tags cannot meet the budget before any alignment runs, so a 15-sample DArTag run takes 75 s against 41 s (a prototype without the prescreen took 150–290 s). `--gapped-rescue off` -restores the 0.9 assignment path; QC reports `reads_assigned_gapped`. +restores the 0.9 assignment path, and QC reports `reads_assigned_gapped`. **Review fixes adopted.** The pooled denoising pass now folds an evidence-failing sequence only into a protected parent carrying the same -target allele (0.9.x moved reads across alleles); parent ranking is -closest-first, then deepest; an observed N counts as a mismatch and -N-bearing tags are credited to their unique compatible sequence or dropped, -never emitted; a k-mer repeated at two positions inside one target frame no -longer anchors reads (it kept only its last position); `merge-pairs` keeps +target allele (0.9.x moved reads across alleles). Parent ranking is +closest-first, then deepest. An observed N counts as a mismatch, and the +pipeline credits N-bearing tags to their unique compatible sequence or +drops them, never emitting them. A k-mer repeated at two positions +inside one target frame no longer anchors reads (it kept only its last +position). `merge-pairs` keeps R2's extension when the reads differ in length and errors on mates out of -step; `window-scan` takes `--scan-seed` for a random sample subset and +step. `window-scan` takes `--scan-seed` for a random sample subset and `--generate-args` to forward evidence flags to the candidate runs. The per-sample cache format is 0.5.0, so existing caches rebuild once. **Considered and not adopted, with the measurement.** Collapsing reads onto -IUPAC-coded canonical tags: DArT uses those codes to encode real secondary -SNPs, and on the blackberry panel the collapse lost 272 vendor-matching -rows and moved count agreement from 0.982 to 0.976 — so rows stay exact -and ambiguity-coded canonicals keep reporting zero exact counts. A -synthesized-primer mask (worse still on blackberry), an unconditional -merge of indel families in long homopolymer runs (it absorbed 66 real -indel alleles on the DArTag project at its Ion-safe default), a -hard-coded ubiquity filter, and a single-gap-only indel tier with its -downstream-context columns were all left out in favour of the one +IUPAC-coded canonical tags failed because DArT uses those codes to encode +real secondary SNPs. On the blackberry panel the collapse lost 272 +vendor-matching rows and moved count agreement from 0.982 to 0.976, so +rows stay exact and ambiguity-coded canonicals keep reporting zero exact +counts. The release left out a synthesized-primer mask (worse still on +blackberry), an unconditional merge of indel families in long homopolymer +runs (it absorbed 66 real indel alleles on the DArTag project at its +Ion-safe default), a hard-coded ubiquity filter, and a single-gap-only +indel tier with its downstream-context columns, in favour of the one mechanism above. -**Validation, identical inputs, 0.9.1 → 0.10.0 — every platform in the -corpus.** Delta smelt GT-seq vs the BWA/bcftools VCF 98.80% → **99.49%** -R1-only and 98.80% → **99.49%** on the merged tiled panel (core 99.80%; -358/361 markers ≥90%); oyster AgriSeq vs Torrent VariantCaller 94.51% → -**94.91%** (markers ≥90%: 460 → 472); honeybee AgriSeq chip 2 vs the -vendor caller 91.60% → **93.84%**, replicate concordance across 30 pairs -97.64% → **98.49%**, depth per sample-marker +28%; cranberry Flex-Seq -(24-sample subset, pooled mates, frozen K4 panel) vs the truth VCF 94.50% -→ **94.78%** on 3.8% more callable cells; vitis rhAmpSeq MM531, 165 -progeny, 193,737 → **202,811** calls (+4.7%) at within-parental-four -transmission 99.890% → **99.894%**, and the 16-sample head-to-head against -`analyze_amplicon` 93.0% → **94.9%** exact agreement at 99.953% Mendelian -consistency; the three in-house DArTag projects `validate`d against their -vendor MADCs kept every substitution-side number (sweetpotato count -Pearson 0.9992 → 0.9993, red clover 0.9733 → 0.9733, blackberry 376 -samples 0.9814 → 0.9814) while adding 1,544 / 2,393 / 8,313 indel-type -rows respectively — rows the vendor pipeline structurally cannot report — -and the private DArTag project (15 checked samples): 2 → **348 of 447** -assembly-predicted indel microhaplotypes recovered at 97% read recall, -including 72–82% of those with two or more indel events, while the new -heterozygotes those rows create have allele fractions indistinguishable -from vendor-agreeing heterozygotes and a third are confirmed by the same -sample's genome assembly. Indel-rich loci gain reads (about 60 markers +**Validation on identical inputs, 0.9.1 → 0.10.0, for every platform in +the corpus.** Delta smelt GT-seq vs the BWA/bcftools VCF rose 98.80% → +99.49% R1-only and 98.80% → 99.49% on the merged tiled panel (core +99.80%, 358/361 markers ≥90%). Oyster AgriSeq vs Torrent VariantCaller +rose 94.51% → 94.91% (460 → 472 markers ≥90%). Honeybee AgriSeq chip 2 +vs the vendor caller rose 91.60% → 93.84%, with replicate concordance +across 30 pairs 97.64% → 98.49% and depth per sample-marker +28%. +Cranberry Flex-Seq (24-sample subset, pooled mates, frozen K4 panel) vs +the truth VCF rose 94.50% → 94.78% on 3.8% more callable cells. Vitis +rhAmpSeq MM531, 165 progeny, rose 193,737 → 202,811 calls (+4.7%) at +within-parental-four transmission 99.890% → 99.894%, and the 16-sample +head-to-head against `analyze_amplicon` rose 93.0% → 94.9% exact +agreement at 99.953% Mendelian consistency. The three in-house DArTag +projects `validate`d against their vendor MADCs kept every +substitution-side number (sweetpotato count Pearson 0.9992 → 0.9993, red +clover 0.9733 → 0.9733, blackberry 376 samples 0.9814 → 0.9814) while +adding 1,544 / 2,393 / 8,313 indel-type rows respectively, rows the +vendor pipeline structurally cannot report. In the private DArTag +project (15 checked samples), recovered assembly-predicted indel +microhaplotypes rose 2 → 348 of 447 at 97% read recall, including 72–82% +of those with two or more indel events. The new heterozygotes those rows +create have allele fractions indistinguishable from vendor-agreeing +heterozygotes, and the same sample's genome assembly confirms a third of +them. Indel-rich loci gain reads (about 60 markers more than doubled on that project, the same set two independent indel implementations found), and Ion row counts rise about 9% (5,890 → 6,443 -on oyster) as slippage haplotypes are now assigned rather than dropped; -their target base is still read correctly, which is why SNP accuracy -rose. Two vendor-agreement effects are expected and explained: DArT emits +on oyster) as the pipeline now assigns slippage haplotypes rather than +dropping them. It still reads their target base correctly, which is why +SNP accuracy rose. Two vendor-agreement effects are expected and +explained. DArT emits N-bearing rows that 0.10.0 never does (29 of the 30 sweetpotato rows that "disappeared"), and at indel-shifted rows inside the substitution envelope the vendor classifies at the fixed offset while 0.10.0 reads through the gap (153 sweetpotato rows, mostly vendor `Other` becoming Ref/AltMatch or -Ref/AltMatch swapping) — the smelt truth VCF settled that question in +Ref/AltMatch swapping). The smelt truth VCF settled that question in favour of the gapped reading. Where an indel allele carries the alternate base, the recovered rows create heterozygotes the vendor calls homozygous -(red clover: updog dosage agreement with the vendor MADC 97.86% → 95.95% at -DP≥10, 13,797 new indel-driven heterozygotes). The 152-progeny red clover -mapping family with both parents adjudicates them: with every MADC pushed +(in red clover, updog dosage agreement with the vendor MADC fell 97.86% → +95.95% at DP≥10, with 13,797 new indel-driven heterozygotes). The +152-progeny red clover mapping family with both parents adjudicates +them. With every MADC pushed through the same updog (diploid, norm) fit, the Mendelian-violation rate is -1.59% under the vendor MADC, 1.61% under 0.9.1 and **1.30% under 0.10.0** -on 2% more tests (parents DP≥20, progeny DP≥10, MPP≥0.9) — the new +1.59% under the vendor MADC, 1.61% under 0.9.1 and 1.30% under 0.10.0 +on 2% more tests (parents DP≥20, progeny DP≥10, MPP≥0.9). The new heterozygotes are inherited, and the vendor's disagreement is the vendor missing real alleles. **Band width.** `--max-indel-length` 10 is the validated default. On the private DArTag project's full 558-sample order, band 10 recovered 374 of -the 447 read-supported assembly-predicted indel microhaplotypes (84%; the -extra samples let 26 more clear the reproducibility route than in the -15-sample run) and band 20 recovered 393 (88%) by adding exactly 76 rows — -all 11–20 bp indel haplotypes, median ~5,600 reads each — with the same -row-plausibility profile, vendor SNP concordance within 0.04 pp -(97.87% vs 97.83% over 1.5M cells) and equal runtime. That order also +the 447 read-supported assembly-predicted indel microhaplotypes (84%, as +the extra samples let 26 more clear the reproducibility route than in the +15-sample run), and band 20 recovered 393 (88%) by adding 76 rows, all +11–20 bp indel haplotypes with a median of ~5,600 reads each. The wider +band kept the same row-plausibility profile, vendor SNP concordance within +0.04 pp (97.87% vs 97.83% over 1.5M cells) and equal runtime. That order also carries a 264-progeny F2 family and three genotypes in technical -quadruplicate, which arbitrate the rows directly: indel-haplotype calls +quadruplicate, which arbitrate the rows directly. Indel-haplotype calls fall inside the founders' four haplotypes at 99.86–99.96%, the same rate -as substitution haplotypes (99.91–99.94%; the vendor's own rows 99.95%), -and an indel haplotype called in one replicate is re-called in its twins -98.4% of the time against 99.3% for substitution haplotypes — inherited -alleles, with the replicate gap consistent with indel alleles amplifying a -little less efficiently. Widen the band on -panels where long indels are expected; the composition guard, not the -band, is what keeps paralogs out. - -**Annotations: `MarkerType`, `Variants`, and the variants sidecar -(`--annotations on`, the default).** Two vendor statistics this pipeline -never computes are repurposed, header included, and a sidecar is written -next to the table; `--annotations off` restores the exact vendor header +as substitution haplotypes (99.91–99.94%, and the vendor's own rows +99.95%). An indel haplotype called in one replicate is re-called in its +twins 98.4% of the time against 99.3% for substitution haplotypes. These +are inherited alleles, and the replicate gap fits indel alleles +amplifying a little less well. Widen the band on panels where long +indels are expected. The composition guard, not the band, keeps +paralogs out. + +**The `MarkerType` and `Variants` annotations and the variants sidecar +(`--annotations on`, the default).** The pipeline repurposes two vendor +statistics it never computes, header included, and writes a sidecar +next to the table. `--annotations off` restores the exact vendor header and writes no sidecar. The column positions are unchanged, so positional consumers see the same 16-column layout. -- `AvgPIC` becomes **`MarkerType`**: what the row carries *beyond its - canonical*, derived from its Variants. The Ref row is `.`; the Alt row - is labelled by the design itself (`snp` for a designed SNP, `indel` for - a designed indel); every other row by its events once the marker's - designed events are removed: `snp` (substitutions only), `indel` (gaps - only), `both`, or `.` (no concrete event beyond the canonical — a row - that merely realises an ambiguity code). A downstream user who wants +- `AvgPIC` becomes `MarkerType`, which records what the row carries + *beyond its canonical*, derived from its Variants. The Ref row is `.`. + The design itself labels the Alt row (`snp` for a designed SNP, `indel` + for a designed indel). Every other row takes its label from its events + after removing the marker's designed events, so it is `snp` + (substitutions only), `indel` (gaps only), `both`, or `.` (no concrete + event beyond the canonical, as in a row that merely realises an + ambiguity code). A downstream user who wants SNP-only microhaplotypes drops `indel`/`both` rows by this label alone and keeps designed-indel markers intact. -- `PICSnp` becomes **`Variants`**: the row's events against the Ref tag, - one token per event, `;`-separated, in 1-based coordinates on the tag as - printed (design strand; a consumer that knows the strand flips them, as - it already does for substitutions). Substitutions are `91:A>T`; - insertions and deletions are VCF-anchored on the preceding reference - base and left-normalised (`55:C>CAAAA`, `70:TAG>T`); then comes the - window geometry a fixed-length row cannot show: `clip=k` when an - insertion pushed the last *k* Ref bases out of the window, `overhang=k` - when a deletion pulled *k* downstream bases in. The Ref row is `.`, the - Alt row of a designed SNP is exactly the design (`46:C>G`), and an - AltMatch row lists the designed substitution among its events. A - position where the Ref tag carries an ambiguity code is never an event - (a concrete base realises the code), matching the IUPAC handling - elsewhere. -- **`OUTPUT.variants.csv`** lists the same events one per line — +- `PICSnp` becomes `Variants`, which lists the row's events against the + Ref tag, one token per event, `;`-separated, in 1-based coordinates on + the tag as printed (design strand, and a consumer that knows the strand + flips them, as it already does for substitutions). Substitutions are + `91:A>T`. Insertions and deletions are VCF-anchored on the preceding + reference base and left-normalised (`55:C>CAAAA`, `70:TAG>T`). Then + comes the window geometry a fixed-length row cannot show, with `clip=k` + when an insertion pushed the last *k* Ref bases out of the window and + `overhang=k` when a deletion pulled *k* downstream bases in. The Ref + row is `.`, the Alt row of a designed SNP is exactly the design + (`46:C>G`), and an AltMatch row lists the designed substitution among + its events. A position where the Ref tag carries an ambiguity code is + never an event (a concrete base realises the code), matching the IUPAC + handling elsewhere. +- **`OUTPUT.variants.csv`** lists the same events one per line, as `CloneID, AlleleID, AlleleSequence, Position, Ref, Alt, Type` with Type `snp`, `ins`, `del`, `clip` (Ref holds the unobserved bases) or - `overhang` (Alt holds the pulled-in bases) — keyed by CloneID and + `overhang` (Alt holds the pulled-in bases). It is keyed by CloneID and sequence so it survives allele-ID renumbering downstream. -Every row is described by its cheapest reading against Ref — a gapped -reading only when strictly cheaper than substitutions — through the -alignment with the fewest gap openings among equal-edit ones (a -three-state banded table), so an inserted block is one event even where -its bases happen to match the reference, as an affine-gap aligner would -describe it. Rows of a marker whose own Alt differs from Ref by a gap -are always read with gaps, so an AltMatch of a designed insertion that -adds one SNP lists the inherited insertion plus the SNP (and is labelled -`snp`) rather than a run of shifted substitutions; because MarkerType is -derived from the same events, the two annotations cannot disagree. -Canonical tags that share an ambiguity code are scored as matching at -that column by the alignment, its prescreen and the substitution count -alike — the relation `tag_mismatches` uses. Rerunning an output with +The pipeline describes every row by its cheapest reading against Ref (a +gapped reading only when strictly cheaper than substitutions), through +the alignment with the fewest gap openings among equal-edit ones (a +three-state banded table). An inserted block is therefore one event even +where its bases happen to match the reference, as an affine-gap aligner +would describe it. Rows of a marker whose own Alt differs from Ref by a +gap always get a gapped reading, so an AltMatch of a designed insertion +that adds one SNP lists the inherited insertion plus the SNP (and carries +the label `snp`) rather than a run of shifted substitutions. MarkerType +comes from the same events, so the two annotations cannot disagree. +The alignment, its prescreen and the substitution count alike score +canonical tags that share an ambiguity code as matching at that column, +which is the relation `tag_mismatches` uses. Rerunning an output with `--annotations off` removes a sidecar left by an earlier run. A -microhaplotype with several SNPs and indels is simply a longer -list: phase lives in the row, and a per-site consumer emits one record +microhaplotype with several SNPs and indels gives a longer list. Phase +lives in the row, and a per-site consumer emits one record per event, which is what `BIGr::madc2vcf_all` does today for -substitutions by realigning each row to Ref. Checks: the Alt-row token +substitutions by realigning each row to Ref. In the checks, the Alt-row token reproduces the design's own `position:Ref>Alt` for 3,120/3,120 sweetpotato, 3,005/3,015 blackberry-design, 2,982/3,000 red clover and 3,030/3,040 private-DArTag-panel loci (every remainder is an Alt tag that -is not a single SNP — ambiguity codes, or a vendor Alt tag that carries -an 8-bp insertion, reported as such); replaying each annotated row's -events onto its Ref tag returns the row's own sequence for all 9,430 -annotated rows of the public sweetpotato plate (16,954 rows; 43,766 +is not a single SNP, such as ambiguity codes, or a vendor Alt tag that +carries an 8-bp insertion, reported as such). Replaying each annotated +row's events onto its Ref tag returns the row's own sequence for all 9,430 +annotated rows of the public sweetpotato plate (16,954 rows with 43,766 substitutions, 1,700 insertions, 1,830 deletions), the delta smelt GT-seq -run (1,775 rows) and the private project's 15-sample run (9,430 rows; a +run (1,775 rows) and the private project's 15-sample run (9,430 rows, a median of two events per annotated row, 41 on the most heavily -substituted one); the annotations add no measurable runtime (the 15-sample -run: 78.7 s off, 76.8 s on). Row counts by +substituted one). The annotations add no measurable runtime (the +15-sample run took 78.7 s off and 76.8 s on). Row counts by label (`marker_types`) and by event kind, plus the sidecar path (`variants`), are in the QC summary. -Consumers: HapApp's fixed-allele-ID step keeps columns 1–3 plus the +Among consumers, HapApp's fixed-allele-ID step keeps columns 1–3 plus the samples, so these columns do not travel through it to -`BIGr::madc2vcf_all` (the sidecar does not need to); BIGr's raw-MADC +`BIGr::madc2vcf_all` (the sidecar does not need to). BIGr's raw-MADC readers (`get_countsMADC`, `filterMADC`) drop statistics columns by -name, so until `MarkerType` and `Variants` are on their list, files -headed there should be generated with `--annotations off` or the two -names added; polyRAD's `readDArTag` and HapApp locate samples -positionally and are unaffected. +name, so until `MarkerType` and `Variants` are on their list, generate +files headed there with `--annotations off` or add the two names. +polyRAD's `readDArTag` and HapApp locate samples positionally and are +unaffected. ## Raw deliveries, tag reconstruction and denoiser scaling (0.12.0) -Three changes made while setting up the alfalfa (DAl21-5779, DAl21-6024) -and pecan (DPec23-8107) panel-paper datasets, none of which alters a table -produced from a preprocessed delivery: +Three changes came out of setting up the alfalfa (DAl21-5779, DAl21-6024) +and pecan (DPec23-8107) panel-paper datasets, and none of them alters a +table produced from a preprocessed delivery. **Raw DArT deliveries.** Older DArT FASTQs keep the inline barcode and the library's common sequence `GATGGATCCAGTGC` in front of every amplicon -(alfalfa 2021: 12 + 14 bases, then the 54-bp tag, on 83-bp reads; pecan -2023: the same 26 bases, the 81-bp tag, then adapter and poly-G on 138-bp -reads), so nothing is primer-started and a 0.11.0 run assigned no read. +(alfalfa 2021 has 12 + 14 bases, then the 54-bp tag, on 83-bp reads, and +pecan 2023 has the same 26 bases, the 81-bp tag, then adapter and poly-G +on 138-bp reads), so nothing is primer-started and a 0.11.0 run assigned no read. `generate --leading-anchor SEQ` and `infer-design --leading-anchor SEQ` cut each read where the anchor ends (it must end within 40 bases beyond -its own length) and count reads without it as `reads_no_leading_anchor`; -the anchor is part of the cache key, the provenance line and the QC +its own length) and count reads without it as `reads_no_leading_anchor`. +The anchor is part of the cache key, the provenance line and the QC parameters (so assignment caches written by 0.11.0 rebuild once, as they -did when the partial-read length joined the key). Both commands check the first files before any read pass: -when almost no read starts with a panel tag but most carry one after a +did when the partial-read length joined the key). Both commands check +the first files before any read pass. +When almost no read starts with a panel tag but most carry one after a constant prefix, the run stops and names that prefix (the suffix shared by the bases in front of the tag at the modal offset, sampled across files so per-sample barcodes do not survive), and `--leading-anchor auto` applies the detected sequence instead (`leading_anchor_detected` in the QC). A -preprocessed delivery passes the check silently (red clover: 87% of reads -start with a panel tag, 0.3% carry one further in), and `auto` refuses on -it rather than cutting anything. Measured: alfalfa assigns 5–6% more reads -per sample than the vendor counted, as the other DArTag panels do; the -primer-free route on the raw alfalfa reads, with no primer file, resolves -2,999 of 3,000 loci in the exact tier, all identical to the design tags. - -**Design route: a tag carries its variant.** Tag reconstruction from the +preprocessed delivery passes the check silently (in red clover, 87% of +reads start with a panel tag and 0.3% carry one further in), and `auto` +refuses on it rather than cutting anything. In the measurements, alfalfa +assigns 5–6% more reads per sample than the vendor counted, as the other +DArTag panels do. The primer-free route on the raw alfalfa reads, with +no primer file, resolves 2,999 of 3,000 loci in the exact tier, all +identical to the design tags. + +**One substitution in the leading anchor (0.14.0).** A read whose common +sequence carries a sequencing error has no exact anchor, and 0.13.0 +counted it as `reads_no_leading_anchor`. With +`generate --leading-anchor-mismatches 1`, such a read is cut +after the one placement within a single substitution in the search window +and counted as `reads_leading_anchor_mismatch`. An exact copy is tried +first, so a read that has one is cut as before. A read with no such +placement, or more than one, still counts as having no anchor. The match +counts substitutions only, but an indel at the anchor's last base reads as +one substitution there, and the cut is then one base off. On made-up reads +such a read then finds no primer (`reads_no_primer`). An anchor shorter than 12 +bases is always matched exactly. The setting joins the cache key only when +an anchor is matched with a substitution. `infer-design` still matches the +anchor exactly, since its reads only vote. The default is `0`. On the alfalfa +cohort `1` added 715 rows (213,514 reads); 531 of them are one G>T away from +their Ref or Alt row, and 20 are in the vendor's table. +Measured on the salmon 3K DArTag plate (DSalm21-6350, 1,104 raw FASTQs, +54-bp tags, `--gapped-rescue off`): with `0`, the table is byte for byte +the 0.13.0 table after the provenance cell. With `1`, reads without an +anchor fall from 13,505,332 to 2,048,910 (2.4% to 0.4% of reads), +2,789,193 more reads are assigned (+1.06%) and 2,304,149 more reach emitted +rows (+0.90%, and 0.65% to 3.20% per sample). 16 new rows pass the evidence +rules, none is lost and no row changes category. The Alt fraction per +marker and sample (depth of 20 or more) changes by 0.0000 at the median and +0.0185 at the 99th percentile, and 379 of 2,501,106 cells move by more than +0.05. Against the vendor MADC, recall is unchanged (99.50%), precision goes +from 77.40% to 77.27% (the 16 rows), and the share of cells with exactly +the vendor's count rises from 64.65% to 66.95%. In one sample, 2,441 of +5,468 recovered on-target reads had the substitution at the anchor's last +base (C read as T in 2,223), spread over 1,106 markers. + +**In the design route, a tag carries its variant.** Tag reconstruction from the primer table and probe design now keeps only the primer-started windows that contain the bracketed variant. The pecan design has one marker -(Chr04_45131234) whose target carries a duplicated primer-bearing flank; -both placements showed the Ref base at the variant offset and the marker -was reported as ambiguous. With the rule, the pecan design tags match the -vendor's Ref/Alt rows at 3,100 of 3,100 markers (3,084 identical, 16 under -vendor IUPAC codes). Any DArT marker table with `MarkerName` and a bracket -`TargetSequence` serves as the probe design, extra markers included. +(Chr04_45131234) whose target carries a duplicated primer-bearing flank. +Both placements showed the Ref base at the variant offset, so the design +route reported the marker as ambiguous. With the rule, the pecan design +tags match the vendor's Ref/Alt rows at 3,100 of 3,100 markers (3,084 +identical, 16 under vendor IUPAC codes). Any DArT marker table with +`MarkerName` and a bracket `TargetSequence` serves as the probe design, +extra markers included. **Denoiser scaling.** At the default distance of 1 the eligible parents of a sequence are its single-substitution neighbours, which `denoise_counts` now enumerates and looks up once the centroids outnumber those neighbours -(the scan stays cheaper at an ordinary locus with a few dozen centroids; -the choice is made per sequence); the selection is identical (a randomized test checks it against the scan, and -the sweetpotato table regenerates byte-identically from cache, and the alfalfa tables re-stamped with 0.12.0 are byte-identical in body to the ones made with the 0.11.0 denoiser). -The pecan panel has one paralogous locus (Chr04_23494647: reads 10–16 +(the scan stays cheaper at an ordinary locus with a few dozen centroids, +and the function chooses per sequence). The selection is identical (a +randomized test checks it against the scan, the sweetpotato table +regenerates byte-identically from cache, and the alfalfa tables +re-stamped with 0.12.0 are byte-identical in body to the ones made with +the 0.11.0 denoiser). +The pecan panel has one paralogous locus (Chr04_23494647, with reads 10–16 mismatches from the design tags around a GGGGGG homopolymer, about 6,000 -unique sequences per sample, 409 rows in the vendor table) that made the -old pass quadratic: its finalisation ran for more than 90 minutes before -being stopped, and completes in minutes now. The locus is not flagged in -the generate QC yet; a per-locus diversity and paralog warning is the -natural next addition. +unique sequences per sample, and 409 rows in the vendor table) that made +the old pass quadratic. Its finalisation ran for more than 90 minutes +before being stopped, and now completes in minutes. The generate QC does +not flag the locus yet, and a per-locus diversity and paralog warning is +the natural next addition. -80 unit tests. +At 0.12.0, the test suite had 80 unit tests. -**0.12.1: the finalisation runs across the workers.** `generate`'s +**In 0.12.1 the finalisation runs across the workers.** `generate`'s finalisation (protection, per-sample denoising, the pooled pass, the -bookkeeping) ran in one process; on a family of 169 rhAmpSeq runs with +bookkeeping) ran in one process. On a family of 169 rhAmpSeq runs with 150-bp windows and 637K reads per sample (311K distinct sequences per sample, 67 per locus, so the lookup rule above never triggers) that stage took 107 minutes against 32 for the eight-worker assignment. Stage timers -(`finalize: ... in N s` on stderr) showed where it went on a 44-run family: -protection 30 s, per-sample denoise 154 s, pooled pass 1,123 s. Both +(`finalize: ... in N s` on stderr) showed where it went on a 44-run +family, with protection at 30 s, per-sample denoise at 154 s, and the +pooled pass at 1,123 s. Both denoising passes are independent per unit of work, the per-sample pass per sample and the pooled pass per locus (its aggregate, the protected set and the gapped classifier that checks a move keeps the target allele), so @@ -1309,149 +1378,842 @@ byte-identically from cache). Protection, the final bookkeeping and the table write stay in the main process. The table is unchanged with `--jobs 1`. +**Raw deliveries with barcodes of several lengths (0.14.0).** The 0.12.0 +detection of the leading anchor pooled the +sampled reads and built the anchor from the prefixes at the modal tag +offset. DArT inline barcodes have 10 to 14 bases, about a fifth of the +samples each, so of 8 sampled files only two or three sit at the modal +offset, and the anchor grew into the barcode bases those few shared. On +the salmon validation plate (DSalm21-6350: 1,104 FASTQs, 2,979 loci, +common sequence `CGATGGATCCAGTGC` in the delivery's targets file; three +truncated files left out of the draws), detection from random subsets of +1, 2, 3 and 4 files (60 draws each) and of 8 files (150 draws) returned +the exact 15 bases in 0, 9, 19, 39 and 133 draws. Of the 17 misses with 8 +files, 13 were one base too long and 4 two. A barcode on this plate ends +in A, G or T, 30–36% each, so an anchor one base too long fits about a +third of the samples and the others lose every read. + +Detection now works per file. A barcode is constant within a file, so +each file gives one prefix, the most common among its shifted reads +(seen at least twice). That also absorbs a tag found a base early, which +the modal offset used to. The anchor is the longest suffix that every +file's prefix shares, and the check samples 24 files instead of 8. On the +same draws the exact sequence came back in 0, 39, 57, 58 and 150, and in +150 of 150 draws of 16 and of 24 files. In 3,000 further draws of 8 files +two anchors were one base too long, about what the barcode endings +predict (the chance that 8 barcodes end alike is 1 in 1,900). In 1,000 +further draws of 24 files none was. Sampling 24 files of the plate takes +about 0.02 s. + +Two rules cover files that are not one clean sample. A file that mixes +barcodes has its prefix shortened until 90% of its shifted reads would be +cut by it. The plate's three truncated files are such files (variants of +one barcode, the commonest in 18–27% of the shifted reads), and alone each gives +the common sequence plus the 2 or 3 bases its variants share, which cuts +95–96% of its tag-carrying reads. Files holding 90% of the shifted reads +must end in the same 8 bases, and the rest are set aside, so a failed +sample does not hide the anchor. + +With up to 24 files the sample is the whole run, and the anchor is in +every file's prefix by construction. It then cuts every file where the +amplicon starts, even when it is longer than the common sequence: from +one file it is the whole prefix, barcode included, and from two files it +kept one to five barcode bases in 21 of 60 draws. In 40 draws each of 1, 2 +and 3 files, the detected anchor was found in at least 97% of the +tag-carrying reads of every file in the run. So `auto` uses an anchor from +fewer than three files and warns not to reuse it for other samples, and +the stop message for an undeclared prefix says the same. + ## Truncated reads: partial-read salvage with a locus guard (0.11.0) A DArTag order whose delivered files were trimmed to 109–113 bp per file, with several amplicons 1–9 bases shorter than the 109-bp window, showed -what the 0.10 rule "reads shorter than the tag are dropped" costs: two loci +what the 0.10 rule "reads shorter than the tag are dropped" costs. Two loci with 101- and 102-bp amplicons had no reads at all in the table (the vendor -counted 104,507 and 69,381), a Y-specific locus lost 46 of 211 carrier -samples because one plate's reads were 106 bp, and in cells where one -allele's amplicon is shorter than the other's every read of that allele was -discarded, so the cell was called homozygous for the other allele (546 +counted 104,507 and 69,381), and a Y-specific locus lost 46 of 211 carrier +samples because one plate's reads were 106 bp. In cells where one +allele's amplicon is shorter than the other's, the rule discarded every +read of that allele, so the pipeline called the cell homozygous for the +other allele (546 Ref reads of 109 bp against 478 Alt reads of 108 bp in one sample). **Truncated reads support alleles but never invent them (partial-read -salvage, on by default).** Reads shorter than the window — adapter- or -quality-trimmed reads at amplicons a few bases short of the tag, or files -trimmed to fewer bases than the tag — are primer-assigned and then credited -to the one full-length allele that has already earned a row and of which the -read is an exact prefix. Two guards -keep this from moving a call: the read must be longer than the longest +salvage, on by default).** The pipeline primer-assigns reads shorter than +the window (adapter- or quality-trimmed reads at amplicons a few bases +short of the tag, or files trimmed to fewer bases than the tag) and then +credits them to the one full-length allele that has already earned a row +and of which the read is an exact prefix. Two guards keep this from +moving a call. The read must be longer than the longest prefix shared between any two learned alleles of its locus (a locus credits truncated reads for both target alleles or for neither, so a ratio can never shift, and a read that does not reach the target base is always ambiguous), and `--min-partial-length` defaults to `--tag-length` minus 9, -so at most nine tail bases are unobserved and primer-dimer fragments never -qualify. Defaults: `--partial-read-mode assign`; `off` restores the drop -behaviour. An `extend` mode that borrowed the design Ref suffix to turn an -unmatched prefix into a provisional allele existed through 0.11.0 and was -removed: on the project above it manufactured a RefMatch row from a 30-bp -primer-dimer. A tag table that carries identical Ref +so at most nine tail bases go unobserved and primer-dimer fragments never +qualify. The default is `--partial-read-mode assign`, and `off` restores +the drop behaviour. An `extend` mode that borrowed the design Ref suffix +to turn an unmatched prefix into a provisional allele existed through +0.11.0 and is now gone, because on the project above it manufactured a +RefMatch row from a 30-bp primer-dimer. A tag table that carries identical Ref and Alt tags (presence/absence designs) shares its whole tag between the two -alleles, so no partial is ever credited at such a locus. The QC reports `partial_reads_assigned`, -`partial_reads_ambiguous` and `partial_reads_unmapped` per sample. The -minimum partial length is part of the cache fingerprint, so runs that relied -on the old default of 30 rebuild their cache once. +alleles, so the pipeline never credits a partial at such a locus. The QC +reports `partial_reads_assigned`, `partial_reads_ambiguous` and +`partial_reads_unmapped` per sample. The minimum partial length is part +of the cache fingerprint, so runs that relied on the old default of 30 +rebuild their cache once. **Measured on that project (564 samples, 3,040 markers, band 20).** The default salvage credits 3.04M reads (+0.98%) to 37,359 cells at 979 loci, makes 15,987 more cells callable for dosage, and raises count agreement with the vendor on the 24,755 shared rows (Pearson r over nonzero cells) from -0.961 to 0.971, because the vendor counts these near-full reads too; dosage +0.961 to 0.971, because the vendor counts these near-full reads too. Dosage agreement with the vendor moves from 97.83% to 97.85% on 1.53M cells, and BIGr `madc_summary` missingness (cells under 10 reads) falls from 7.55% to -6.62% overall against the vendor's 6.74% (per-sample median 7.20% → 6.22% -against 6.38%). The locus guard, run against the same cache without it, removes 504,677 of the -salvaged reads from 7,914 cells at 269 loci — loci with a learned Match row -that differs from Ref or Alt only beyond the truncated length — and reverts +6.62% across all cells against the vendor's 6.74% (per-sample median +7.20% → 6.22% against 6.38%). The locus guard, run against the same cache +without it, removes 504,677 of the salvaged reads from 7,914 cells at 269 +loci, which are loci with a learned Match row that differs from Ref or +Alt only beyond the truncated length. It also reverts 469 of the 472 dosage-class changes that unguarded crediting introduces. The 2,316 cells (0.15%) whose dosage class differs from the no-salvage table are the allele-specific amplicon-length cases above, which the no-salvage -table calls homozygous; two independent instruments say the new calls are -right: their haplotypes fall within the locus's four founder haplotypes in -the F2 families at 99.8% (GEN, n=1,067) and 100% (DV, n=558), the F2 rate, -and re-call in technical replicates at 98.6% against 98.5% for the calls -they replace, while the vendor's own call agrees with the new call in 1,276 -of 2,164 cells and with the old one in 737. Reads that stop before the -target (a 35-bp junction product at one Y-specific locus, 90-bp amplicons -whose target sits beyond them, primer-dimers) stay out: they are below the -length minimum, and would be ambiguous between Ref and Alt even above it. +table calls homozygous. Two independent instruments show that the new +calls are right. Their haplotypes fall within the locus's four founder +haplotypes in the F2 families at 99.8% (GEN, n=1,067) and 100% (DV, +n=558), the F2 rate, and re-call in technical replicates at 98.6% +against 98.5% for the calls they replace. The vendor's own call agrees +with the new call in 1,276 of 2,164 cells and with the old one in 737. +Reads that stop before the target (a 35-bp junction product at one +Y-specific locus, 90-bp amplicons whose target sits beyond them, +primer-dimers) stay out, because they are below the length minimum and +would be ambiguous between Ref and Alt even above it. The assign stage adds under a minute to a 50-minute run. The preamble now records `min_partial_length=` beside `partial_read_mode=`. -**Measured on three other DArTag panels (salvage on against off; same code, -scripts and band 10).** Sweetpotato (80 samples, 81-bp tags): +40,438 reads -(0.04%) at 304 loci; 5 of 196,494 called dosage cells change class and the -vendor's own call agrees with the salvaged class in all 5; leaf/root -replicate re-call 90.11% either way; count correlation with the vendor table -0.9993 → 0.9997. Red clover (376 samples, 109-bp tags, primer-free panel): -+941,538 reads (1.3%) at 823 loci, 8,733 more callable cells, 786 of 717,768 -called cells change class (the vendor sides with the salvaged class in 714, -with the unsalvaged in 14); dosage agreement 96.87% → 96.98%, count -correlation 0.9765 → 0.9845. Blackberry (376 samples, 109-bp tags): -+1,552,191 reads (0.76%) at 634 loci, 6,160 more callable cells, 2,112 of -1,006,967 change class (1,994 against 50); dosage agreement 95.18% → 95.39%, -count correlation 0.9823 → 0.9867. Rows are identical in every pair: a -partial read never establishes one. The credited reads sit at loci whose +**Measured on three other DArTag panels (salvage on against off, with the +same code, scripts and band 10).** Sweetpotato (80 samples, 81-bp tags) +gains +40,438 reads (0.04%) at 304 loci. Of 196,494 called dosage cells, +5 change class, and the vendor's own call agrees with the salvaged class +in all 5. Leaf/root replicate re-call is 90.11% either way, and count +correlation with the vendor table goes 0.9993 → 0.9997. Red clover (376 +samples, 109-bp tags, primer-free panel) gains +941,538 reads (1.3%) at +823 loci and 8,733 more callable cells, and 786 of 717,768 called cells +change class (the vendor sides with the salvaged class in 714, with the +unsalvaged in 14). Dosage agreement goes 96.87% → 96.98% and count +correlation 0.9765 → 0.9845. Blackberry (376 samples, 109-bp tags) gains ++1,552,191 reads (0.76%) at 634 loci and 6,160 more callable cells, and +2,112 of 1,006,967 change class (1,994 against 50). Dosage agreement goes +95.18% → 95.39% and count correlation 0.9823 → 0.9867. Rows are +identical in every pair, because a partial read never establishes one. +The credited reads sit at loci whose amplicons run short of the tag, where the counts land on the vendor's totals -(one red clover locus: 2,606 → 83,324 reads against the vendor's 83,303); -loci whose amplicons are shorter than the partial minimum (78–84 bp at the -largest red clover examples) or whose reads end before the distinguishing -base stay uncredited, by design. +(one red clover locus went 2,606 → 83,324 reads against the vendor's +83,303). Loci whose amplicons are shorter than the partial minimum (78–84 +bp at the largest red clover examples) or whose reads end before the +distinguishing base stay uncredited, by design. -**One reading per row (0.11.0).** 0.10.0 read a row twice: classification +**One reading per row (0.11.0).** 0.10.0 read a row twice. Classification confirmed a gapped reading on a unit-cost traceback with the composition guard and the 12-base verified suffix, while `Variants`/`MarkerType` took the fewest-openings alignment unconfirmed, so a row could list an indel its category ignored, or be classified through a gap its annotation placed -elsewhere. Both now use `row_reading`: the cheaper of the two +elsewhere. Both now use `row_reading`. The cheaper of the two substitution-only readings is the bound, the fewest-openings alignment is -the reading, and it is accepted only when verified by GAP_VERIFIED_SUFFIX -bases after its last gap and well composed — composition being judged on -the equal-edit explanation that needs the fewest substitutions -(`fewest_substitution_alignment`), because the fewest-openings explanation -trades a gap opening for a substitution wherever it can, and against the -canonical the row is read from, so a designed substitution never counts -against an AltMatch row's indel reading. A reading that fails is not a -reading of the row at all: the row is classified at the fixed offset and -described as substitutions, by both consumers. On the project above this +the reading, and the function accepts it only when GAP_VERIFIED_SUFFIX +bases after its last gap verify it and it is well composed. It judges +composition on the equal-edit explanation that needs the fewest +substitutions (`fewest_substitution_alignment`), because the +fewest-openings explanation trades a gap opening for a substitution +wherever it can, and against the canonical the row is read from, so a +designed substitution never counts against an AltMatch row's indel +reading. A reading that fails is not a reading of the row at all. Both +consumers then classify the row at the fixed offset and describe it as +substitutions. On the project above this re-labelled 76 of 28,793 rows (53 `Other` rows became RefMatch/AltMatch, 16 swapped between RefMatch and AltMatch, 7 became `Other`) and rewrote the annotation of 554 rows whose listed indel sat inside the last 12 bases or -whose composition failed the guard (`both`/`indel` → `snp`); counts moved by +whose composition failed the guard (`both`/`indel` → `snp`). Counts moved by 97 reads in 66 rows through the category-aware pooled denoise. -**Freeze health (0.11.0).** Freezing a window panel (`--reuse-tags`) is -what keeps haplotype identity comparable across runs, but read geometry +**Freeze health (0.11.0).** Freezing a window panel (`--reuse-tags`) +keeps haplotype identity comparable across runs, but read geometry drifts run to run and a frozen window can slide off the reads a new run delivers. `normalize-reads --reuse-tags` therefore still runs the coverage -pass fresh placement would use and scores every frozen window against it: -the QC's `markers` table carries each window's predicted full coverage on +pass fresh placement would use and scores every frozen window against it. +The QC's `markers` table carries each window's predicted full coverage on this run beside the window fresh placement would choose today and its coverage, and `freeze_health` summarises the read-weighted coverage of the frozen panel against the fresh one, the markers losing more than ten -points, and the ten worst. One line on stderr says what freezing costs -this run; `--window-placement center` skips the pass. The excised FASTQs -and the tag table are unchanged by the check. +points, and the ten worst. One line on stderr reports what freezing costs +this run, and `--window-placement center` skips the pass. The check +leaves the excised FASTQs and the tag table unchanged. **Vendor-only markers, re-derived.** Of the 53 markers in the tag table that had no reads in the 0.10 table, 46 carry vendor counts (40,101 called -cells): 33 markers (29,861 cells) have only primer-bearing fragments that -end before the target (the vendor counts them as Ref), 10 (8,478 cells) -have 44–77-bp amplicons that do contain the target — recoverable only by a -per-locus window, not by salvage — or, for two of them, reads that are -largely absent from the delivered files, 2 (1,762 cells) have 101/102-bp -amplicons and are counted since 0.11.0, and 7 have no reads anywhere and no -vendor counts. The 46 markers whose vendor Ref and Alt rows are identical -are a separate class: their target sits at position 110, one base past the +cells). By class, 33 markers (29,861 cells) have only primer-bearing +fragments that end before the target (the vendor counts them as Ref), and +10 (8,478 cells) have 44–77-bp amplicons that do contain the target, +recoverable only by a per-locus window and not by salvage, or, for two of +them, reads that are largely absent from the delivered files. Another 2 +(1,762 cells) have 101/102-bp amplicons, which the pipeline has counted +since 0.11.0, and 7 have no reads anywhere and no vendor counts. The 46 +markers whose vendor Ref and Alt rows are identical are a separate class. +Their target sits at position 110, one base past the 109-bp window (the vendor's SNP report lists them without a position, and the 110th base segregates in the plates whose reads are longer than 109 bp). +## Genome paralog filter (`filter-paralogs`, 0.14.0) + +On the public lettuce 3K DArTag data about two thirds of the reads come from +paralogous copies. A paralog read that carries the target base becomes a +RefMatch/AltMatch row, and `BIGr::madc2vcf_all` sums it into the target SNP, +so inbred lines look heterozygous. Raising `generate --min-identity` removes +the diverged copies but not the close ones. `filter-paralogs` is an opt-in +filter for such panels. It reads any MADC, from MADCATS or the vendor, with +or without the preamble, so it also filters vendor deliveries, and HapApp's +fixed-allele-ID output (columns `Code_version`, `AlleleID`, `CloneID`, +`AlleleSequence` and samples, IDs such as `|Ref_0001`, and merged counts +written as `12.0`). The command lives in `madcats_paralogs.py`, which imports +the MADC helpers it shares with `validate` from `madcats`, and `build_parser` +imports it when it builds the parser. Run as `python3 madcats.py`, the file +is `__main__`, so it registers itself as `madcats` before the filter module +imports it. Otherwise the module would load a second copy whose `MadcError` +`main` does not catch. + +Design: + +- **Aligner.** The command uses minimap2 through `mappy`, an optional extra + imported only by this command, so MADCATS still has no required + dependency. The index is a standard `-x sr` index (k=21, w=11). At map + time the command allows single-seed chains (`min_cnt=1`, + `min_chain_score=20`) and 50 hits (`best_n`). mappy reports neither AS + nor XS, so the command recomputes each hit's DP score from CIGAR, NM, + matching bases and block length with the pinned short-read scoring + (+2/−8, gaps 12+2 or 24+1, ambiguous −1). Ties are exact. +- **Marker placement.** The command aligns each marker's Ref tag and keeps + every equal-best site the search returns. It reads the CloneID + `CHROM_POS` as a position on the genome given. The position picks among + equal-best Ref-tag sites and stands in (±tag length) when the Ref tag does + not align. When no equal-best site covers it, the command realigns the Ref + tag to a k=11 index of the window around the position (±tag length + + 20 bp), and an alignment covering the position becomes the marker's site + (`clone_id_site`), even when the tag scores better elsewhere. Without one + the marker is `unplaced`. `--clone-positions ignore` turns these uses off, + for a genome other than the one the CloneIDs refer to. On the lettuce + vendor MADC against v8 it changes 11 markers. The 9 fallback windows + become `unplaced`, keeping 1,032 rows labelled `paralog`, and 1 tie stays + multi-copy. `Chr2_001081815` goes back to Chr4, dropping 11 rows that + `use` keeps. The id95 labels do not change. +- **Labels.** Each haplotype gets its best score at its marker's site and + its best score elsewhere. A haplotype that scores higher at the marker is + `on_target`, one that scores higher elsewhere is `paralog`, and a tie is + `ambiguous`. The command also realigns every haplotype to a k=11 index of + its own marker's sites (±20 bp), and the site score is the higher of that + and the genome-wide hit there. Without that realignment, 18% of id95 + haplotypes had no hit at their own marker, and 326 that bwa places on + target were unmapped. Each marker's sites get an index of their own, so + markers sharing a site never compete for the preset's hit limit. Hits are + one locus when they share at least half of the shorter interval, both + when the command merges a sequence's hits and when it matches a hit to its + marker's site. +- **Actions.** The command drops paralog and ambiguous rows by default, or + flags them in the `PICRef` column, renamed `GenomeLabel`. It never drops + canonical rows. Every input row, dropped or kept, gets a line in the + labels sidecar. + +Measurements (lettuce v8 genome, 2.4 Gb, 12-core laptop): + +| | id95 MADCATS MADC | DArT vendor MADC | +|---|---|---| +| Rows / distinct sequences | 17,847 / 17,846 | 732,534 / 732,154 | +| Run time, prebuilt index | 12 s (8 threads) | 2 min 15 s (8 threads), 9.4 GB | +| Rows kept | 12,695 | 113,667 | +| Reads in paralog rows | 16.0% | 63.3% | +| Keep/drop agreement with bwa-mem labels | 98.2% | 94.9% | +| Keep/drop agreement with the bwa prototype's output, rows / reads | 98.2% / 99.7% | 94.9% / 99.4% | +| Het rate (proxy), unfiltered → prototype → `filter-paralogs` | 12.6% → 6.44% → 6.40% | 19.9% → 6.79% → 7.02% | + +Indexing took 50 s and 10.6 GB at peak, and the `.mmi` is 5.7 GB. The het +proxy sums Ref+RefMatch and Alt+AltMatch reads per marker and sample, calls +cells with ≥10 reads, and counts het where the minor allele has ≥10%. The +bwa-mem labels came from aligning the same haplotypes with `bwa mem -T 20` +(AS > XS unique). Variants tried and rejected: + +- With default sr chaining, keep/drop agreement on id95 was 97.3%, against + 98.2% with single-seed chains and `best_n` 50. +- A k=15, w=10 index gave a DArT agreement of 94.4%, against 94.9% with + k=21, and slower mapping. +- Also dropping site-realigned DArT haplotypes with ≥6 mismatches gave a + het proxy of 6.93%, against 7.02%. The rest of the gap to bwa is minimap2 + finding fewer distant copies of highly diverged vendor haplotypes. + +Count overflow. The lettuce vendor MADC stores counts in a signed byte, so +90,913 cells across 1,108 markers are negative (minimum −128) and the +largest count is 127. Counts of 128–255 appear as count − 256 +(adding 256 matches MADCATS's counts for the same cells), and counts of 256 +or more wrap silently. `read_madc` (and so `validate`) and `filter-paralogs` +now warn and record `count_overflow` in their reports. They never correct +the counts, since the wrapped ones are indistinguishable from real small +counts. The figures in the table above use the counts as stored. + +HapApp layout. The id95 MADC rewritten in HapApp's layout (fixed IDs, +leading `Code_version`, every tenth row's counts as floats) gets the same +label, action and scores for all 17,847 rows as the raw MADC, and the same +QC totals. Moving the command into its own module left the id95 output, both +sidecars included, byte-identical. + +Review fixes. An external review of the first version (cd2d7cb) gave a +counterexample for each of the defects below, and each is now a test +(`ReviewCaseTests`, and `FilterTests` with the fake aligner). Effects on +the lettuce MADCs, default `use` mode: + +| Fix | Effect | +|---|---| +| Ref tag realigned at its CloneID position on disagreement | For `Chr2_001081815` the genome-wide search returned 51 hits, best on Chr4 (96), none at its Chr2 design site (156). Placed on Chr2, 11 of its 14 dropped DArT rows become `on_target` | +| Every haplotype scored at its own site, and the higher of the two scores kept | 530 DArT rows that the shared site index had crowded out get a site score, and 1 row (`Chr5_323370531`, genome-wide 86 at the site, 88 elsewhere, 94 realigned) becomes `on_target` | +| One locus rule for merging hits and for target membership | No label changes, but 850 DArT sequences had adjacent hits merged before | +| Every equal-best Ref-tag site kept for placement | No lettuce Ref tag has more than 8 | +| Multi-part `.mmi` refused | The lettuce index is one part, and reading its layout takes 0.03 s | + +Together, 12 DArT rows (994 reads) go from dropped to kept and none the +other way. Keep/drop agreement with bwa-mem on the 726,693 DArT Match/Other +rows with bwa labels rises from 94.8128% to 94.8136% (+6 rows), and id95 +labels do not change (97.3484% on 11,842 rows). The DArT run took 76 s, +against 78 s for cd2d7cb in the same session. +For `Chr2_001081815`, both the hit limit and the ambiguity codes matter. The +vendor tag, or the tag with R and M read as N, misses the design site at +`best_n` 50, 200 and 1,000 and finds it at 5,000. With the codes resolved +to bases the search finds it at `best_n` 50. bwa agreement is concordance, +not truth, and source-known fixtures for both errors (target evidence +removed, paralog evidence kept) are still missing. + +Module audit. A code and test audit of `madcats_paralogs.py` identified and +fixed three defects: + +| Defect | Effect before | Now | +|---|---|---| +| A minimap2 index in several parts was refused only as `--genome-index` | Given as `--genome` it loaded, mappy searched its first part, and the command judged markers on later contigs without their own site | Refused whichever option names it | +| `validate` and `filter-paralogs` took a processed MADC's `readCountSum` column for a sample | QC read totals of `filter-paralogs` doubled, and `validate` listed it among the samples | Skipped by the helper both use | +| A run that failed while writing (a non-numeric count in a late row) | A truncated MADC and labels file stayed on disk | Removed | + +The rest changed no output. `filter_paralogs`, 211 lines doing five jobs, is +now five functions, and both passes read their rows through one generator. +The command checks the MADC's header before it loads the index. Names and +comments now agree with the code. They say that a marker's CloneID position +places it as well as its Ref tag, that the score is that of the reported +alignment and not minimap2's `AS`, and that the genome-wide search returns +up to 51 hits and not 50. The module says what is minimap2's (Li 2018 and +Li 2021) and what is MADCATS's own. +The outputs of eight runs on the data below were the same before and after, +byte for byte, and the same on one thread and on four. + +Both passes skip rows with an empty `AlleleID`, or too short to hold the +identity columns, and the QC totals do not count them. That is now +documented and tested. Counting them would add a key to the QC JSON and was +left for a decision. + +What the kept rows of the vendor MADC are. The filter keeps 113,667 of the +lettuce DArT MADC's 732,534 rows. Read counts in this paragraph and the next +add 256 to the negative cells. + +| Kept rows | Rows | Share of the kept reads | +|---|---|---| +| Canonical Ref and Alt, `on_target` | 5,687 | 87.5% | +| RefMatch, AltMatch and Other, `on_target` | 105,913 | 12.4% | +| `unmapped`, and 9 canonical rows kept despite their label | 2,067 | 0.1% | + +Most of the 105,913 are not haplotypes that recur in the germplasm. In +89,070 of them (84%) no sample has 5 reads. Another 8,779 reach 5 reads only +in 25 samples that stand apart from the other 351. The 25 are the samples in +which the designed alleles hold less than three quarters of the kept reads +(4 to 71%, against a median of 90% in the others), and the filter drops +76.1% of their reads at the median, against 57.5%. The sample table names +them (PI accessions, SAL lines, IVT 280, UC96US23, two other lines and two +mixes of Salinas DNA with one of them) but not their species. Of the +remaining rows, 6,367 reach 5 reads in one to four of the 351 samples and +1,697 in five or more. These 1,697, at 1,037 markers, hold 95% of the reads +that all 105,913 rows have in the 351 samples, and 1,290 of them are within +3 differences of the reference at their site. bwa mem keeps 71% of the +105,913 rows and 92% of their reads. + +Lettuce against blastn. blastn 2.17.0 (`-task blastn -word_size 11`, no +masking, as for alfalfa below) aligned a sample of 18,763 rows of the vendor +MADC to the v8 genome. Each row got a label from the bit scores by the +filter's rule, with the marker's site widened by 20 bases as its home. The +sample holds every kept `on_target` RefMatch, AltMatch and Other row that +has 5 reads in a sample and reads in 5 samples ("well supported"), and +random draws of the other rows. The whole table would have taken about 11 +hours on 8 threads. "Same decision" is to keep or to drop, as the default +does. + +| Rows | In the sample | Filter and blastn, same decision | Filter and bwa mem | bwa mem and blastn | +|---|---|---|---|---| +| Dropped as `paralog`, well supported | 3,000 of 65,119 | 99.6% | 99.8% | 99.5% | +| Dropped as `paralog`, others | 2,000 of 528,208 | 99.4% | 99.2% | 99.0% | +| Dropped as `ambiguous` | 1,500 of 25,540 | 91.5% | 89.3% | 87.2% | +| Kept as `on_target`, well supported | 8,763 of 8,763 | 68.9% (88.9% of reads) | 80.4% | 85.0% | +| Kept as `on_target`, others | 3,000 of 97,150 | 50.8% (71.1% of reads) | 71.9% | 75.3% | +| `unmapped`, which the filter keeps | 500 of 2,056 | 7.2% | 31.2% | 74.4% | + +The three agree on what the filter drops. They differ on what it keeps, and +the difference grows with the row's distance from the reference at its own +site (the score lost there, 10 for a substitution). Of the well-supported +kept rows: + +| Distance from the site | Rows | Share of their reads | Kept by bwa mem and by blastn | Dropped by both | +|---|---|---|---|---| +| 1 to 3 | 3,726 | 76.9% | 97.4% | 0.8% | +| 4 or 5 | 2,001 | 12.0% | 71.2% | 12.3% | +| 6 or more | 3,036 | 11.1% | 27.4% | 42.5% | + +blastn aligns 86% of the rows 6 or more from the site over the whole tag +there, at 95% identity or less, so they are diverged sequences and not +partial reads. The genome-wide search seeds with 21 bases and misses copies +of such sequences that bwa mem and blastn find, while the realignment at the +site seeds with 11. Of the 1,697 rows that recur in the 351 samples, both +aligners keep 1,480 (87%, with 91% of the reads) and both would drop 122 +(7%, with 5%). Rows the filter keeps and bwa mem would drop hold 0.97% of +all kept reads, well-supported rows that blastn would drop hold 1.26%, and +well-supported rows that both would drop hold 0.71%. These reads are +concentrated. Of 2,986 markers, 61 have a tenth or more of their kept reads +in rows bwa mem would drop, 61 in rows blastn would, 33 in rows both would, +and 10 have a quarter or more in rows both would. blastn places 90% of the +sampled `unmapped` rows elsewhere, but all 2,056 of them hold 26,000 reads. +So both aligners confirm the rows the filter drops, and it keeps about 1% of +reads that they would not, in rows far from the reference. The two aligners +share the reference with the filter, and their agreement is still not truth. + +Delta smelt GT-seq, placement against the primers. The public delta smelt +GT-seq dataset (Zenodo 10.5281/zenodo.19069550, 96 samples) provides a second +species and platform along with an independent answer for where each marker +lies. That answer is the 81 bases from its forward primer, +found by exact search of both primers in the genome (GCA_021917145.1, +437 Mb). The MADC has 368 markers, 1,527 rows and 10.2 million reads. + +| Run | Markers at the expected site | Unplaced | Rows labelled | +|---|---|---|---| +| CloneIDs renamed to CHROM_POS of the target | 368 | 0 | 1,527 on_target | +| The same, `--clone-positions ignore` | 368 | 0 | 1,527 on_target | +| 29 markers' positions moved 5,000 bases and 15 put on another chromosome | 324 | 44, the moved ones | 1,350 on_target, 177 unplaced | +| The same, `--clone-positions ignore` | 368 | 0 | 1,527 on_target | +| CloneIDs as generated (locus names such as `NC_061060_1_U618`) | 354 | 14 | 1,494 on_target, 33 unplaced | + +The filter labelled no row `paralog` or `ambiguous` and dropped none. The +panel has no paralogs in this genome, so this checks placement and false +positives. A marker with a wrong position is left unplaced, not misplaced. +In the last run 100 locus names end in an underscore and digits, and the +filter reads them as CHROM_POS. For 14 the number is not within the tag and +the marker stays unplaced. The filter takes a CloneID that looks like a +position for one, which `--clone-positions ignore` avoids. Eight runs took +38 s on four threads, building the index once. + +Planted paralogs. The record above says the agreement with bwa mem is +concordance and that cases with a known answer were still missing. They +were built in the smelt genome. For each of 105 markers drawn at random, a +changed copy of the genome around its tag (the tag and 100 bases either +side) went into the genome as a contig of its own, and the MADC got the rows +a co-amplified copy would give (the copy's tag, and that tag with one more +substitution, with half the Ref row's reads each). The runs used fifteen +markers per class, three random draws, CloneIDs in CHROM_POS form and the +default options: + +| Planted copy | Rows from the copy labelled `paralog` | Rows of the marker itself labelled `on_target` | +|---|---|---| +| None (263 markers per draw) | | 3,348 of 3,348 | +| 1 substitution from the Ref tag | 90 of 90 | 173 of 179 (4 `ambiguous`, 2 `paralog`) | +| 2 substitutions | 90 of 90 | 168 of 170 (2 `ambiguous`) | +| 4 substitutions | 90 of 90 | 165 of 165 | +| 8 substitutions | 90 of 90 | 183 of 183 | +| 1 substitution and a 2-base deletion | 90 of 90 | 167 of 167 | +| Identical copy | | 1 of 192 and 191 `ambiguous`, of which the filter kept 90 canonical rows | +| 4 substitutions, copy not added to the genome | 0 of 90 because all are `on_target` | 177 of 177 | + +- The filter labelled every row from a copy that is in the genome `paralog` + and dropped it, 450 of 450, and mislabelled no row of an unplanted marker. +- Of the 864 rows of markers with a copy in the genome, the filter lost 8 + rows, all at copies one or two bases from the Ref tag. An allele of the + marker that is as near the copy as its own site is `ambiguous`, and one + that carries the copy's base is the copy's sequence. +- An identical copy makes the marker's rows `ambiguous`, and the default + drops them and keeps the canonical Ref and Alt rows. +- The filter cannot see a copy that is not in the assembly, so it keeps that + copy's rows as alleles of the marker. + +The same design, twenty markers on a random genome, is in the test suite +(`PlantedCopyTests`). + +Alfalfa, two aligners and two families. The alfalfa 3K panel is a second real +panel with paralogs, in an autotetraploid, and its public data allow three +checks that the lettuce record lacks. They place each marker from more +sequence than its tag, label each row with two other aligners, and map each +row genetically. + +- The MADCs are the two F1 families of the G3 article jkag131, with fixed + allele IDs. I195 x J432 has 186 samples, 2,999 markers and 7,517 rows of + 54-base tags, and E115 x F628 has 374 samples, 2,989 markers and 8,731 + rows of 81-base tags. The filter also ran on the panel's haplotype + database (23,469 haplotypes, Zenodo doi:10.5281/zenodo.10681524) as a + third table. +- The first genome is the monoploid assembly of cultivar Bolivia + (GCA_051527215.1, eight gapless chromosomes, 776 Mb), a genome of another + cultivar than the panel's. The panel's 361-base design sequences differ + from it at a median of 3 bases, and at 17 or more for a tenth of the + markers. The second is the genome the panel was designed on, chromosome + set 1 of XinJiangDaYe (see "The design genome" below). The first shows + what a user gets without the design genome, the second what the filter + does in its intended use. +- A marker's home on this genome is where its design sequence (180 bases + either side of the target, from the panel's probe table) aligns. bwa mem + placed 2,745 of the 3,000 uniquely and minimap2 2,780. The 2,735 that both + place uniquely are at the same base in both, and are the markers judged + below. Another 22 have a unique place on a chromosome with another number + than the panel names, and the rest have no unique place. +- Each table had two runs, one with `--clone-positions ignore`, as a user + must run it on a genome the CloneIDs do not refer to, and one with the + default after renaming the CloneIDs to the chromosome and target position + on this genome, as it runs on a design genome. The first run took 47 s and + 5.2 GB with the index built, the others 7 to 8 s. + +Placement, for the markers with a home: + +| | E115 x F628, 81-base tags (2,730 markers) | I195 x J432, 54-base tags (2,734) | +|---|---|---| +| `ignore`, at home | 2,669 | 2,487 | +| `ignore`, several equal-best sites with one at home | 17 | 28 | +| `ignore`, somewhere else | 15 | 25 | +| `ignore`, not placed | 29 | 194 | +| Positions on this genome, at home | 2,730 | 2,727 (7 not placed) | + +Without positions, the filter places a Ref tag that differs from this genome +where it matches best, or nowhere. It puts 0.5 to 0.9% of the markers in +another copy and leaves 1% (81 bases) to 7% (54 bases) unplaced, keeping all +their rows. With positions, it aligns the tag again at its own site and +places every marker but seven. + +Rows and reads by label, with positions. In E115 x F628 7,928 rows are +`on_target` (90.9% of reads), 357 `paralog` (4.3%), 297 `ambiguous` (3.8%), +9 `unmapped` and 140 `unplaced` (0.9%). The filter drops 437 rows with 4.1% +of the reads and keeps 217 canonical rows with 4.0% despite their label. In +I195 x J432 the shares are 88.7%, 4.7%, 4.5%, 0.3% and 1.8%, and the filter +drops 4.2% of the reads. Of the database's 23,469 haplotypes 1,145 are +`paralog` and 930 `ambiguous`. Lettuce lost 63% of its reads, while alfalfa +has little to remove. + +Labels against bwa mem and blastn. bwa mem (`-a -k 12 -T 20`) and blastn +(word size 11, no masking) each aligned every row to the same genome, and +each row got a label from the aligner's own score by the rule the filter +uses. The best score is at home, is equalled elsewhere, or is elsewhere. The +table counts rows of the markers placed at home. "Same decision" joins the +labels by what the default does with the row, which keeps `on_target` and +`unmapped` and drops `paralog` and `ambiguous`: + +| Table, run | Rows | Same label and same decision as bwa mem | Same label and same decision as blastn | +|---|---|---|---| +| E115 x F628, positions | 7,916 | 99.42%, 99.81% | 99.42%, 99.68% | +| E115 x F628, `ignore` | 7,716 | 99.49%, 99.86% | 99.49%, 99.74% | +| I195 x J432, positions | 6,768 | 98.63%, 99.44% | 98.73%, 99.56% | +| I195 x J432, `ignore` | 6,145 | 99.27%, 99.56% | 99.35%, 99.63% | +| Haplotype database, positions | 21,155 | 99.14%, 99.53% | 98.90%, 99.28% | +| Haplotype database, `ignore` | 20,551 | 99.17%, 99.54% | 98.99%, 99.35% | + +bwa mem and blastn give each other the same decision for 99.82% and 99.65% of +the two families' rows and 99.37% of the database's, so the filter is as near +to each of them as they are to one another. For RefMatch and AltMatch rows alone the filter and bwa mem +agree on 99.5% (81 bases) and 98.8% (54 bases). All 297 rows the filter calls +`paralog` in E115 x F628 are `paralog` for bwa mem. + +Where the rows map genetically. In a full-sib family a haplotype is inherited +with the haplotypes near it on the same chromosome copy, so across the +progeny its share of the marker's reads rises and falls with theirs, and a +row from a paralogous copy follows the haplotypes around that copy instead. +For each row whose share varies in the family, the check finds the ten rows +of other markers that correlate with it most strongly (0.4 or more in +absolute value, three or more needed) and looks up their markers' homes. The +row is linked at home when 60% or more of them lie within 15 Mb of its +marker, and linked elsewhere when 60% or more lie on one chromosome and +fewer than 20% near the marker. No alignment of the row enters this. + +| Family, run | Rows judged | Kept rows linked at home | Rows labelled `paralog` that are linked elsewhere, at home with the other site far away, and at home with it near | +|---|---|---|---| +| E115 x F628, positions | 2,877 | 2,701 of 2,768 (97.6%) | 38, 7, 29 | +| E115 x F628, `ignore` | 2,816 | 2,671 of 2,736 (97.6%) | 36, 5, 21 | +| I195 x J432, positions | 2,585 | 2,425 of 2,485 (97.6%) | 22, 4, 31 | +| I195 x J432, `ignore` | 2,408 | 2,286 of 2,340 (97.7%) | 20, 1, 21 | + +- Of the rows the filter keeps, 97.6% map to their marker in both families. + More than half of the others are at some 30 markers where every kept row + maps elsewhere. There the marker itself is somewhere else in the family + than its design sequence is on this genome, which no row label can mend. + The rest, 22 to 28 rows or about 1% of the kept rows judged, are rows from + another place that the filter did not catch, because it cannot see a copy + that this genome lacks or holds in another form. +- Of the `paralog` rows that linkage can decide, 84 to 95% map elsewhere, and + for 25 of 38 and 18 of 22 the region they map to holds the site the filter + named. +- For 21 to 31 `paralog` rows the better site is on the marker's own + chromosome within 15 Mb, for most of them 1 kb to 1 Mb away. Such a copy is + inherited with the marker, so linkage says nothing about them. +- RefMatch and AltMatch rows that map elsewhere are 9.2% of those judged + before the filter and 5.5% after in the larger family, and 8.3% and 5.2% in + the smaller. +- A RefMatch or AltMatch row with reads in every sample of the family is two + to three times as common among `paralog` rows as among `on_target` rows, + at 23% against 8%, and 43% against 13%. + +Genotypes. An experimental beta-binomial genotype caller (`madcats call --prior norm`, +moved to the separate `madcats-call` branch rather than 0.14.0) ran on each +family before and after the filter, and the comparison is with the article's +published dosages, which +come from the same reads. Over the 986 and 974 published targets the share +of equal dosages moved from 89.80% to 89.87% and from 90.11% to 90.33%. Of +the 211 markers that lost a row in the larger family only 29 are among the +published ones (2.9%, against 7.1% of the panel), and there the share rose +from 86.3% to 86.9% with 11% of the genotypes changed. The estimated +overdispersion rose from 40 to 50 and from 30 to 40 because with those rows +gone the counts scatter less. + +A count of the progeny genotypes that the two parents' genotypes cannot give +was tried as a test and is not one. Reads of a paralog make a parent look +heterozygous, and a heterozygous parent allows every progeny genotype, so the +count rewards the rows the filter removes. It was 1.86% before and 2.20% +after at the markers that lost a row. At chr4.1_040870396 it went from 0 to +189 of 372 when the filter dropped one row. That row has a quarter to three +quarters of the marker's reads in every one of the progeny, which no allele +of a tetraploid cross has (two copies in each parent leave 1 progeny in 36 +without it). The row differs from the Ref tag at five bases and matches a +copy 10 kb away better. + +The design genome. The panel's probe table names +`M_sativa_genome_XinJiangDaYe_set1_v1.fasta`, and every CloneID is on a +chromosome named `chrN.1`, so the panel was designed on one of the four +chromosome sets of the XinJiangDaYe assembly (figshare, +doi:10.6084/m9.figshare.12327602, CC BY 4.0, with `chr1.1` to `chr8.4` and +9,789 unplaced sequences). Set 1, `chr1.1` to `chr8.1`, served as the +genome, and the MADCs ran as they are, in the default mode, so that their +own CloneIDs are the positions. bwa mem places 2,984 of the 3,000 design +sequences uniquely and minimap2 2,992, every one at the position its CloneID +names and without a single difference, so here a marker's home is its CloneID +position. + +| | E115 x F628, 81-base tags | I195 x J432, 54-base tags | Haplotype database | +|---|---|---|---| +| Markers placed at their CloneID position | 2,989 of 2,989 | 2,999 of 2,999 | 3,000 of 3,000 | +| Of them, Ref tags with several equal-best sites, settled by the position | 17 | 34 | 17 | +| Rows `on_target`, `paralog`, `ambiguous` | 8,388, 207, 136 | 7,211, 145, 159 | 22,309, 680, 480 | +| Share of reads on those rows | 96.0%, 2.2%, 1.8% | 94.6%, 2.6%, 2.8% | | +| Rows dropped, and their reads | 296, 2.6% | 202, 3.0% | 1,113 | +| Same label as bwa mem, same decision | 99.61%, 99.85% | 99.48%, 99.76% | 99.32%, 99.69% | +| Same label as blastn, same decision | 99.59%, 99.72% | 99.49%, 99.68% | 99.10%, 99.43% | +| Kept rows linked at home | 3,053 of 3,184 (95.9%) | 2,740 of 2,845 (96.3%) | | +| `paralog` rows linked elsewhere, at home with the other site far away, and at home with it near | 29, 3, 27 | 17, 1, 33 | | + +- On the design genome no marker is unplaced or put in another copy, with + CloneID positions or without them (`ignore` leaves the 17 and 34 Ref tags + with several sites unsettled and makes no other change), and the filter + places the 54-base tags as well as the 81-base ones. On the other + cultivar's genome 1 to 7% were unplaced. +- Fewer rows are labelled, with 207 `paralog` and 136 `ambiguous` in the + larger family against 357 and 297 on the other genome, and no row + `unplaced` against 140. A genome of another cultivar makes some alleles + look like copies. +- The filter keeps or drops the same rows as bwa mem for 99.7 to 99.9% and as + blastn for 99.4 to 99.7%, as on the other genome. +- Of the `paralog` rows that linkage can decide, 91% (29 of 32) and 94% (17 + of 18) map elsewhere. Of the kept rows 96% map to their marker, and the + others are mostly at some 60 markers where every kept row maps elsewhere + (102 of 131 rows at 63 markers, and 86 of 105 at 54), where the marker is + somewhere else in the family than in this assembly. Apart from those, 29 + and 19 kept rows, under 1% of those judged, map away from their marker. +- Genotypes do not gain. Against the published dosages the larger family + stays at 89.80% and the smaller goes from 90.11% to 89.93%. In alfalfa the + filter removes 2.6 to 3.0% of the reads, its labels hold up against two + aligners and against inheritance, and it has no measurable effect on the + target genotypes. Alfalfa is a panel that does not need the filter. + +A haplotype-resolved reference. The assembly the alfalfa panel was designed +on has four copies of every chromosome, and the panel used one set of them. +Another tetraploid cultivar whose haplotypes are in the INSDC archives +(RegenSY, with haplotype 3, GCA_054855475, and haplotype 4, +GCA_054883285) shows what the filter does when it gets more than one set. +The genome was chromosomes 1 to 3 of one haplotype, then of both, and the +table was the 3,378 rows of the larger family at the 1,193 markers designed +on those chromosomes. + +| Genome, run | Markers placed at one site | Ref tag with several equal-best sites | Rows `on_target` | `ambiguous` | `paralog` | RefMatch and AltMatch rows dropped | +|---|---|---|---|---|---|---| +| One haplotype, `ignore` | 1,077 | 27 | 2,921 | 115 | 71 | 114 of 992 | +| One haplotype, positions | 1,103 | 16 | 2,954 | 103 | 94 | 115 of 992 | +| Two haplotypes, `ignore` | 648 | 518 | 1,372 | 1,565 | 361 | 655 of 992 | +| Two haplotypes, positions | 1,148 | 29 | 1,171 | 1,490 | 670 | 637 of 992 | + +With the second haplotype in the genome the filter drops two thirds of the +RefMatch and AltMatch rows where it dropped one in nine, and keeps 1,271 to +1,523 Ref and Alt rows only because it always keeps canonical rows. A row +that is the other haplotype's allele matches that haplotype better and is +labelled `paralog`, and one that both haplotypes carry is `ambiguous`. +CloneID positions place the markers (1,148 at one site against 648) and do +not help the rows. + +The design assembly itself says the same. With sets 1 and 2 of XinJiangDaYe +as the genome and the larger family's whole MADC, 1,199 of the 2,989 Ref +tags have an identical copy on set 2 (all settled by the CloneID position), +3,757 rows are `ambiguous` and 1,229 `paralog` where 136 and 207 were, and +the filter drops 1,969 of the 2,753 RefMatch and AltMatch rows where it +dropped 296. It keeps 3,017 Ref and Alt rows only as canonical rows. +Indexing two sets (1.6 Gb) took 8.3 GB of memory, and three sets and all +four (2.7 Gb) did not fit in the 13 GB available here. A polyploid or +haplotype-resolved assembly has to be cut down to one set of chromosomes +before it goes to the filter, and for this panel that is set 1. + +This record does not cover FASTQs of this panel, and so a MADC from +`generate` (a search found no public alfalfa DArTag reads), or planted +copies in these genomes. + +Tiled markers with the paralog filter. `generate` credits a read +that fits several tiles of one amplicon to each of them (`--tile-groups`). +That work and the paralog filter were written on separate branches and +first met at the merge. A synthetic panel checks them together +(`tests/test_tiled_markers.py`). It has two tiles with variants at tag +positions 31 and 56 of one 81-base window, a third marker elsewhere, ten +diploid samples with every combination of the two variants, and the tags +written both ways a tile's tag can carry the other tile's variant, as an +ambiguity code (the DArTag way) and as the reference base. + +- `generate` gives both tiles all 60 reads of every sample. With ambiguity + codes in the tags no read equals a Ref or Alt tag, so those two rows are + empty and every read is on a RefMatch or AltMatch row. A genotype taken + from the Ref and Alt rows alone would have no reads. +- `filter-paralogs` places both tiles at the one site and labels every row + `on_target`, so the filtered table is the same as its input. + +## How `generate` reads rows, and primer removal (0.14.0) + +The changelog says what each change does. The figures here are from the pecan, sweetpotato, +alfalfa and blackberry DArTag cohorts and from three sets of simulated haplotypes. + +**Unresolved ends.** 2.2% to 3.2% of rows get the `unresolved` token (0.7% to 2.0% of reads), and +0.12% to 0.22% of reads move from `RefMatch` or `AltMatch` to `Other`. None moves to the other +allele. On the simulated haplotypes the rows counted for the wrong target allele fall from 1.2% to +0.13%, and the substitutions written that no haplotype carries from 108,592 to 8,312, while 1.0% +fewer rows are counted for the right allele. Rows without the token are written as before, except +a few whose counts change because the pooled denoiser groups rows by category. Read at the fixed +offsets, as before, such an end shows substitutions that no sample carries, and an insertion or +deletion before the target can put the other allele's base on it. Read through the unverified +gap, it is right more often but shows gaps in rows that have none. + +**A gap before the unresolved end.** A row can carry a real insertion or deletion and, later, a +gap too close to its end to verify. `generate` first read such a row as unresolved from the +earlier gap on. It now keeps an earlier gap when the 12 bases after it read with at most 2 +mismatches, and leaves the row unread only from the later gap on. On haplotypes made up with a +known allele, 2,072 rows go from `Other` to the right allele and 2 to the wrong one. On the real +cohorts, with this and the read-continuation changes below, 18 rows (78,992 reads) leave `Other` +on sweetpotato, 7 (8,444) on pecan and 5 (2,215) on alfalfa. Of the sweetpotato rows whose whole reads were aligned by hand, 34,282 reads now get the +base the read carries and 1,569 the other allele; all 19 rows whose target lies past the row end +stay `Other`. Without the test on the 12 bases, an alfalfa row that is a left primer followed by a +sequencing adapter (43,048 reads, no insert) read as `RefMatch`. Where reads run past the tag, +read continuation is asked first, so a row it can settle is settled as before. + +**Read continuation.** On the simulated haplotypes the rows counted for the right allele rise from +91.7% to 94.8% (v0.13: 92.2%), and unread rows fall from 3.2% to 0.06%. Rows counted for the wrong +allele stay at 0.14% (v0.13: 1.15%). On pecan 140 rows are settled (133,213 reads), and on +sweetpotato 53 (140,465 reads). + +The read pass counts a tag's continuations once a sample has three reads of it, the first two +included, so the order of reads in a FASTQ changes nothing. A continuation counts when 60% of the +tag's reads that reach the compared length carry it. Each tag is compared at the longest length +90% of its own reads reach. As first built, the share was taken over each sample's three commonest +continuations, and nine more pecan rows were settled. Recounted from the reads, the commonest +continuation of those nine has 40% to 59%. In seven of them it is far ahead of the second (45 +reads against 7): read errors scatter the rest. The pooled denoiser reads rows with the same +continuations as the table. + +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 +`AltMatch`. + +**`Variants` from the reading the category came from.** 0.07% to 0.25% of rows get other +`Variants` (28 to 75 rows). With primers kept, no row is left whose `Variants` and category put +different bases on the target. Without primers up to 27 rows per panel still do, nearly all of them +rows of another length than the Ref row, which are read again as printed. + +**Where the right primer cut lands.** Against the full-length reads of a pecan and a sweetpotato +DArTag cohort, 99.4% and 99.2% of reads were in rows cut at exactly the right base. The rest were a +few bases off, with primer bases left or sample bases removed. Nearly all of those rows show five +or fewer bases of the primer, or a primer copy that differs from the primer, or a repeat in which +two cuts fit equally well. The tag itself then cannot settle where the primer starts. An insertion +or deletion within about 5 bases of the right primer is the usual cause. A cut at the designed +position in a row whose last 8 bases and primer bases are as designed was wrong in 0.2% to 0.3% of +rows, and any other cut in 3% to 5%. These figures predate the rule in the next paragraph. Without +primers, the rows of a 54-base alfalfa tag are about 25 bases long. + +**The cut keeps the base a row's category was read from.** 14 rows on pecan and 5 on alfalfa now +keep their right primer, and none on sweetpotato or blackberry. 10 rows on pecan, 17 on alfalfa, 3 +on sweetpotato and 1 on blackberry, all `Other`, are now cut where their primer is found. No row +merges or splits, and no read moves between alleles. Rows whose category and `Variants` disagree +fall from 37 to 27 on pecan and from 22 to 18 on alfalfa. Against pecan's full reads, 7 of the 14 +rows are now cut right or one base late. The other 7 took their category from a primer base, and +now keep 1 to 16 primer bases. + +**Rows of two allele groups stay apart.** Rows that `generate` put in different allele groups can +become the same sequence once the right primer is cut. They now keep their right end and stay +separate. This happens at one alfalfa marker (2 rows) and nowhere on pecan or sweetpotato. There +the tag ends where the primer starts, and the cut removes a last base that is not the primer's. +Merged, 1,378 Alt reads had joined an `Other` row. With primers removed, no read changes allele +group on the three cohorts. + +**Tile groups.** `--tile-groups auto` no longer joins two declared groups through an undeclared +marker. A marker that leads its group has an empty `LocusGroup` cell and now counts as declared. +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, 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, 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 +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`). 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 This pipeline's responsibility ends with generation of the raw MADC-like -microhaplotype count table — and that boundary is certified end-to-end: -MADCATS output has been carried through the full production stack +microhaplotype count table, and end-to-end tests certify that boundary. +They carried MADCATS output through the full production stack (HapApp_utils fixed allele IDs -> `BIGr::madc2vcf_all()` -> updog -dosage) on two platforms and scored against external truth at the far +dosage) on two platforms and scored it against external truth at the far end. On GT-seq the whole downstream stack costs 0.25 points (98.42% at the end of the chain vs 98.67% at the MADC), and the off-target SNPs recovered from Match haplotypes score *higher* than the targets (98.79% on 38,244 additional cells). On the 192-sample capture cohort the chain delivers 95.13% on 295,068 target cells and reproduces the source -publication's population-genetic findings from MADCATS calls alone. Fixed allele-ID assignment and maintenance of the -cross-project panel allele database are downstream HapApp responsibilities; -the former `--allele-catalogue` reprocessing mode was removed accordingly. +publication's population-genetic findings from MADCATS calls alone. Fixed +allele-ID assignment and maintenance of the cross-project panel allele +database are downstream HapApp responsibilities, so MADCATS dropped the +former `--allele-catalogue` reprocessing mode. ## Input contracts @@ -1459,45 +2221,45 @@ The DArT primer CSV must contain: `MarkerName, LeftPrimerSequence, RightPrimerSequence, VariantRef, VariantAlt, VariantPositionInTagSequence`. Indel markers use dash notation (`-` on the empty side, the inserted or deleted bases on the other) with the position -naming where the affected span begins; the pipeline's stored variant +naming where the affected span begins. The pipeline's stored variant position becomes the first base at which the two tags actually differ, which can sit beyond the declared position when the flank repeats the indel content. Primers may contain IUPAC codes (degenerate oligos over flanking -SNPs); tags are reconstructed as the primer sequence verbatim plus the -genomic continuation, matching the vendor's representation. +SNPs). The pipeline reconstructs tags as the primer sequence verbatim plus +the genomic continuation, matching the vendor's representation. The probe-design TSV/CSV must contain `MarkerName` and `TargetSequence`, -with a single bracketed variant — a SNP such as `[C/T]` or an +with a single bracketed variant, either a SNP such as `[C/T]` or an anchored-base indel such as `[A/ACTTG]` or `[TTTTTTG/T]`. Panel construction rejects designs whose variant lies inside the left primer (Alt reads could never carry the primer), identical alleles, and SNP designs whose constructed Alt tag does not appear among the bracket expansions (a primer-table/probe-design disagreement). An optional `LocusGroup` column declares markers as tiles of one physical locus -(see the 0.9.0 section); members of a group must present the same -target region — identical Ref expansions, differing only in which -variant is bracketed — and violations are load-time errors. The +(see the 0.9.0 section). Members of a group must present the same +target region, with identical Ref expansions that differ only in which +variant carries the brackets, and violations are load-time errors. The reference-tags CSV accepts and emits the same optional column, and it only appears in output when some locus actually uses it, keeping ungrouped panels byte-identical to earlier versions. The platform-neutral reference-tag CSV must contain: `MarkerName, LeftPrimerSequence, RefSequence, AltSequence`. Add -`VariantPositionInTagSequence` when Ref and Alt differ at more than one base; -it is validated as an in-range number pointing at an actual Ref/Alt -difference. Identical Ref/Alt sequences or alleles are rejected. +`VariantPositionInTagSequence` when Ref and Alt differ at more than one base. +The pipeline checks that it is an in-range number pointing at an actual +Ref/Alt difference, and rejects identical Ref/Alt sequences or alleles. `VariantRef`, `VariantAlt` (validated for IUPAC compatibility with the tag bases), and `RightPrimerSequence` are optional. Curated tags may contain -IUPAC codes; see the classification note above for what that means for +IUPAC codes. The classification note above explains what that means for canonical counts. -Left primers that are strict prefixes of other panel primers are supported, -and under the default `--primer-mismatches 1` every primer within the -mismatch budget is considered regardless of depth or mismatch count — an -exact short primer cannot suppress a longer one-mismatch primer. Reads -matching several primers are resolved by full-tag identity, and -unresolvable ties are dropped as ambiguous. The default changed from 0 to -1 in 0.9.0: every validated benchmark on every platform ran with 1, and +The pipeline supports left primers that are strict prefixes of other panel +primers, and under the default `--primer-mismatches 1` it considers every +primer within the mismatch budget regardless of depth or mismatch count, so +an exact short primer cannot suppress a longer one-mismatch primer. +Full-tag identity resolves reads matching several primers, and the pipeline +drops unresolvable ties as ambiguous. The default changed from 0 to 1 in +0.9.0, because every validated benchmark on every platform ran with 1, and exact-only matching silently drops Match-haplotype reads whose distinguishing SNP falls inside the assignment anchor, which biases depth by haplotype. Pass `--primer-mismatches 0` to restore exact-only @@ -1507,24 +2269,33 @@ Process a cohort in ONE `generate` invocation whenever novel-allele discovery matters. The evidence model's reproducibility route counts supporting samples within the invocation, so splitting a cohort into several smaller `generate` runs weakens discovery in proportion to the -split: a real haplotype spread thinly across sample subsets can fail -the `--reproducible-min-samples` gate in every subset while easily -passing it cohort-wide (measured on a 192-sample capture cohort -processed as 8 batches: a materially thinner Match-row catalogue than -one full-cohort pass). Batch the expensive `normalize-reads` stage -freely — its outputs 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. +split. A real haplotype spread thinly across sample subsets can fail +the `--reproducible-min-samples` gate in every subset while passing it +cohort-wide (a 192-sample capture cohort processed as 8 batches gave a +materially thinner Match-row catalogue than one full-cohort pass). +Batch the expensive `normalize-reads` stage freely, since its outputs +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; `normalize-reads` accepts any read that contains a panel window. -Paired-end data enters through one of the two 0.9.0 routes — `merge-pairs` -for overlapping pairs, or pooling both mates into one per-sample FASTQ for -non-overlapping dual-anchored designs — chosen explicitly from the assay's -measured geometry. Target manifests (`targets_*.csv`) are optional and used -only for sample names/metadata; by default sample columns use the unique -FASTQ filename stem. +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, +`merge-pairs` for overlapping pairs or pooling both mates into one +per-sample FASTQ for non-overlapping dual-anchored designs. Choose the +route explicitly from the assay's measured geometry. Target manifests +(`targets_*.csv`) are optional and serve only for sample names/metadata. +By default sample columns use the unique FASTQ filename stem. ## Tests @@ -1532,58 +2303,59 @@ FASTQ filename stem. python3 -m unittest discover -s tests -v ``` -The suite contains 59 unit/end-to-end tests, including evidence-route -protection and emission, single-sample depth discovery, the supporting- -frequency floor, exact and fuzzy prefix-nested primer resolution, -design-guard rejections, vendor-preamble sample-ID detection, -read-accounting invariants, infer-design (window enumeration, anchor -selection, exact and fuzzy end-to-end inference, ambiguous-window -exclusion), version 0.7.0's indel and degenerate-primer support (general -window enumeration, indel panel construction with round-trip, end-to-end -indel inference, primer overlay), version 0.8.0's normalize-reads -stage (window-placement invariants, orientation and extraction, and -end-to-end normalization into generation), and version 0.8.1's window -freezing and repeat-aware placement (verbatim `--reuse-tags` round-trip, -shifted-window honoring, design-mismatch refusal, and the tandem-repeat -penalty flipping a near-tied placement off a repeat), and version 0.8.2's -output framing (preamble structure with first-cell provenance and starred -cells, dotted statistics columns, sample-lookup renaming with -incomplete-table refusal, and `read_madc` round-trip of preambled -output), version 0.8.3's per-locus anchors (growth past the minimum -only for colliding prefixes, capped sharing for variant-identical -windows), and version 0.9.0's paired-end and tiling support (pair -merging across extended and engulfed/read-through geometries with -quality-picked overlap bases, locus-group tile routing end to end in -both `nearest` and `covered` modes including the winner-take-all -full-span case, and the distinct-window guard nudging a colliding -tile to its best distinct start and refusing an indistinguishable -homopolymer frame), and the `window-scan` diagnostic (a linked-SNP -fixture where a longer window earns strictly more information at equal -retention, and the scan recommends it), and version 0.10.0's gapped -rescue and review fixes (the bit-vector prescreen against a reference DP -on random indel cases, assignment and through-the-gap classification of -early, two-event and target-deleting indels, the composition guard -refusing a substitution-heavy read, the verified-suffix rule keeping the -substitution reading for a tail shift, closest-parent denoising, the -same-allele pooled pass on a private heterozygote, N-tag crediting and -dropping, intra-target k-mer deletion, R2 extension on unequal-length -merges, mate-ID errors, and the seeded scan subset), plus the second-review -fixes (N reads never credited to an ambiguity-coded canonical, design-side -IUPAC compatibility inside the gapped prescreen and alignment, dropped N -reads counted as window-scan churn, and length validation in the named -FASTQ parser). The diagnostic scripts in `scripts/` refuse -cache directories holding multiple fingerprints for one sample (pass -`--cache-fingerprint` to select one) and are runnable directly without -`PYTHONPATH` tricks. The 0.5.0 refactor was additionally gated on -byte-for-byte regressions: fresh per-sample processing reproduces every -0.4.0 cache payload exactly on all 80 samples, and the new quality-only -configuration reproduces the 0.3.x `full_s5` output file byte-for-byte. +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): + row alignment, unresolved-end handling, read continuation, and Ref/Alt tie-breaking +- `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` + test is skipped when `mappy` is not installed) +- `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 + +Coverage in `test_madcats.py` includes: + +- **Core assignment and discovery:** evidence-route protection and emission, single-sample depth + discovery, the supporting-frequency floor, exact and fuzzy prefix-nested primer resolution, + design-guard rejections, vendor-preamble sample-ID detection, and read-accounting invariants. +- **Design inference and indels (0.7.0):** `infer-design` window enumeration, anchor selection, + exact and fuzzy end-to-end inference, ambiguous-window exclusion, general indel window + enumeration, indel panel round-tripping, end-to-end indel inference, and primer overlay. +- **Normalization, framing, and anchors (0.8.0–0.8.3):** `normalize-reads` window-placement + invariants, orientation, extraction, and end-to-end normalization into `generate`, verbatim + `--reuse-tags` round-trips, shifted-window honoring, design-mismatch refusal, tandem-repeat + penalties, vendor preamble formatting with provenance and dotted statistics columns, + `--sample-lookup` validation, `read_madc` round-trips, and per-locus anchor growth on colliding + prefixes. +- **Paired-end merging, tiling, and window scanning (0.9.0):** pair merging across extended and + read-through geometries with quality-selected overlap bases, `LocusGroup` tile routing in + `nearest` and `covered` modes, distinct-window deduplication and homopolymer guards, and + `window-scan` length selection. +- **Gapped rescue and review hardening (0.10.0+):** Myers bit-vector prescreen parity against + reference DP on random indels, through-the-gap classification of early, two-event, and + target-deleting indels, composition and verified-suffix guards, closest-parent denoising, + same-allele pooled merging on private heterozygotes, N-read crediting and dropping, intra-target + k-mer deletion, R2 extension on unequal-length merges, mate-ID validation, seeded scan subsets, + design-side IUPAC handling during gapped alignment, window-scan N-read churn accounting, and + FASTQ record length validation. + +The diagnostic scripts in `scripts/` refuse cache directories holding multiple fingerprints for one +sample (pass `--cache-fingerprint` to select one) and run directly without `PYTHONPATH` +configuration. Byte-for-byte regressions also gated the 0.5.0 refactor: fresh per-sample processing +reproduces every 0.4.0 cache payload across all 80 samples, and the quality-only configuration +reproduces the 0.3.x `full_s5` output file byte-for-byte. ## Interpretation and references Breeding Insight describes MADC rows as 81-bp amplicon microhaplotypes with -per-sample counts. Ref and Alt contain only the designed target difference; -RefMatch and AltMatch have the respective target base plus other differences. +per-sample counts. Ref and Alt contain only the designed target difference, +while RefMatch and AltMatch have the respective target base plus other +differences. The official format overview is at . diff --git a/docs/src/README.md b/docs/src/README.md index 8417450..ed25383 100644 --- a/docs/src/README.md +++ b/docs/src/README.md @@ -7,13 +7,13 @@ [![Tests](https://github.com/Breeding-Insight/MADCATS/actions/workflows/tests.yml/badge.svg)](https://github.com/Breeding-Insight/MADCATS/actions/workflows/tests.yml) **MADCATS** (Marker-Anchored Discovery and Counting of Alleles from Targeted Sequencing) is a -platform-independent command-line tool that turns targeted-sequencing FASTQs into MADC -microhaplotype count tables. It recovers the alleles a panel was designed to detect, discovers the -additional microhaplotypes present in the reads, and writes a raw MADC table. That table goes -through HapApp (or HapApp_utils) before dosage calling and VCF conversion with BIGr and related -tools. +platform-independent command-line tool that converts targeted-sequencing FASTQ files into MADC +microhaplotype count tables. It counts the alleles a panel was designed to target, discovers +additional microhaplotypes present in the reads, and writes a raw MADC table. Downstream workflows +typically pass this table through HapApp (or HapApp_utils) to assign fixed allele IDs before dosage +calling and VCF conversion with BIGr and related tools. -The name also reflects the tool's origins as a FASTQ-to-MADC workflow, where MADC is the +The name also reflects the tool's origins as a FASTQ-to-MADC workflow, where MADC stands for the *Missing Allele Discovery Counts* format. ## What can MADCATS do? @@ -21,32 +21,40 @@ The name also reflects the tool's origins as a FASTQ-to-MADC workflow, where MAD | Command | Description | |---------|-------------| | [`madcats design`](commands/design.md) | Reconstruct Ref/Alt tags from vendor primer + probe-design files | -| [`madcats infer-design`](commands/infer-design.md) | Infer the panel from the probe design plus reads when the primer file is withheld | +| [`madcats infer-design`](commands/infer-design.md) | Infer the panel from the probe design plus reads when no primer file is available | | [`madcats merge-pairs`](commands/merge-pairs.md) | Merge overlapping paired-end reads into single fragments | -| [`madcats normalize-reads`](commands/normalize-reads.md) | Orient and window non-primer-started reads (e.g. AgriSeq) | -| [`madcats window-scan`](commands/window-scan.md) | Choose the tag/window length from the project's own reads | +| [`madcats normalize-reads`](commands/normalize-reads.md) | Orient and window non-primer-started reads (e.g., AgriSeq) | +| [`madcats window-scan`](commands/window-scan.md) | Evaluate candidate tag lengths using the project's reads | | [`madcats generate`](commands/generate.md) | Generate the MADC count table | | [`madcats validate`](commands/validate.md) | Compare a generated MADC against a reference MADC | +| [`madcats filter-paralogs`](commands/filter-paralogs.md) | Drop or flag MADC rows that a reference genome places at another locus (experimental, requires `mappy`) | ## Key Features -- **Open and deterministic**: every threshold is on the command line, and a QC/provenance JSON is - written beside every result -- **Platform-independent**: validated on DArTag, AgriSeq (Ion Torrent), GT-seq, rhAmpSeq and - Flex-Seq capture data with the same code -- **Evidence-based discovery**: a new microhaplotype is reported only when the reads support it - (see the [evidence model](reference/evidence-model.md)), and denoising never changes a sample's - Ref/Alt dosage -- **Indel-aware**: designed indel markers are fully supported, and undesigned indels are recovered - with a gapped alignment that caps the number of substitutions and gaps -- **No dependencies**: pure Python 3 standard library, with parallel workers and a reusable - per-sample cache - -## A prior MADC is not an input - -Generation uses only the FASTQs plus the assay design: the DArTag primer and probe files, the probe -design alone, or a platform-neutral Ref/Alt tag manifest. A vendor MADC, when you have one, is used -only *after* generation, as an external check with [`madcats validate`](commands/validate.md). +- **Open and deterministic.** Every threshold is configurable on the command line, and MADCATS + writes a QC/provenance JSON file beside every output. +- **Platform-independent.** The same codebase supports and has been validated on DArTag, AgriSeq + (Ion Torrent), GT-seq, rhAmpSeq, and Flex-Seq capture data. +- **Evidence-based discovery.** MADCATS reports a novel microhaplotype only when the reads meet + within-project evidence thresholds (see the [evidence model](reference/evidence-model.md)), + protects canonical and evidence-passing alleles during per-sample denoising, and restricts pooled + merges to the same target allele so cross-sample merging cannot alter Ref/Alt dosage. +- **Indel-aware.** MADCATS supports designed indel markers and recovers undesigned indels using a + banded gapped alignment that caps substitutions and gap length. +- **Zero required dependencies.** Core commands use only the Python 3 standard library, with + parallel sample processing and a reusable per-sample cache. Only the optional genome paralog + filter requires `mappy`. +- **Optional paralog filter (experimental).** For panels where co-amplified paralogs inflate + heterozygosity, [`filter-paralogs`](commands/filter-paralogs.md) drops or flags haplotypes that + align better to another locus in a reference genome. Because this command is new and experimental + in 0.14.0, its options, defaults, and outputs may change in future releases. + +## A prior MADC is not required + +MADC generation uses only the FASTQ files and the assay design, provided as DArTag primer and probe +files, a probe design alone, or a platform-neutral Ref/Alt reference-tag CSV. When a vendor MADC is +available, use it only *after* generation as an external benchmark with +[`madcats validate`](commands/validate.md). ## Quick Example @@ -67,18 +75,20 @@ madcats generate \ ## Getting Started -New to MADCATS? Start here: +New to MADCATS? Begin with these pages: -1. [Installation](getting-started/installation.md): install with pip or download a binary -2. [Quick Start](getting-started/quickstart.md): your first MADC in two commands -3. [Try the Example](getting-started/example.md): run a small simulated project and check it against the truth -4. [Choosing a Workflow](getting-started/workflows.md): which commands your platform and inputs need +1. [Installation](getting-started/installation.md) with pip or a downloaded binary +2. [Quick Start](getting-started/quickstart.md) for your first MADC in two commands +3. [Try the Example](getting-started/example.md) to run a small simulated project and check it + against the truth +4. [Choosing a Workflow](getting-started/workflows.md) to find which commands your platform and + inputs need ## Scope MADCATS is an independent implementation of the MADC format and does not aim to reproduce any -vendor's table exactly. How closely it agrees, and against which comparators, is recorded in -[Validation & Accuracy](reference/validation.md). +vendor's table exactly. [Validation & Accuracy](reference/validation.md) records how closely it +agrees, and against which comparators. ## Getting Help diff --git a/docs/src/SUMMARY.md b/docs/src/SUMMARY.md index 49674f2..999c03c 100644 --- a/docs/src/SUMMARY.md +++ b/docs/src/SUMMARY.md @@ -16,6 +16,7 @@ - [Panels Without a Primer File](tutorials/primer-free.md) - [AgriSeq and Other Non-Primer-Started Reads](tutorials/agriseq.md) - [Paired-End Reads and Tiling](tutorials/paired-end.md) +- [Filtering Paralogs with a Reference Genome](tutorials/paralog-filter.md) # Command Reference @@ -27,6 +28,7 @@ - [madcats window-scan](commands/window-scan.md) - [madcats generate](commands/generate.md) - [madcats validate](commands/validate.md) +- [madcats filter-paralogs](commands/filter-paralogs.md) # Reference diff --git a/docs/src/citation.md b/docs/src/citation.md index b06f7ea..3265151 100644 --- a/docs/src/citation.md +++ b/docs/src/citation.md @@ -19,21 +19,21 @@ BibTeX: } ``` -> **Note:** A formal publication with DOI is planned. This section will be updated when available. +> The authors plan a formal publication with DOI and will update this section when it is available. ## AI Assistance MADCATS was developed in collaboration with Claude Opus 5.5 and Fable 5.1 (Anthropic), which helped write its code and documentation. The authors directed the work, reviewed and tested the -results, and are ultimately responsible for the application. +results, and are responsible for the application. ## Related Resources - Breeding Insight, [MADC file format](https://breeding-insight.github.io/BIGr_documentation/posts/madc-file-format/) - Breeding Insight, [MADC data processing](https://breeding-insight.github.io/BIGr_documentation/posts/madc-data-processing/) -- Breeding Insight, [BIGapp-PanelHub](https://github.com/Breeding-Insight/BIGapp-PanelHub): public panel metadata and design Ref/Alt tags -- Breeding Insight, [dartag_alleles](https://github.com/Breeding-Insight/dartag_alleles): the reference-BLAST / paralog audit pattern -- The sweetpotato DArTag panel publication: [PMC11354173](https://pmc.ncbi.nlm.nih.gov/articles/PMC11354173/) +- Breeding Insight, [BIGapp-PanelHub](https://github.com/Breeding-Insight/BIGapp-PanelHub), with public panel metadata and design Ref/Alt tags +- Breeding Insight, [dartag_alleles](https://github.com/Breeding-Insight/dartag_alleles), for the reference-BLAST / paralog audit pattern +- The sweetpotato DArTag panel publication, [PMC11354173](https://pmc.ncbi.nlm.nih.gov/articles/PMC11354173/) If you call dosages from MADCATS output with updog, please also cite: @@ -42,10 +42,21 @@ Gerard, D., Ferrão, L.F.V., Garcia, A.A.F., & Stephens, M. (2018). Genotyping polyploids from messy sequencing data. Genetics 210(3):789-807. ``` +If you filter a MADC with `madcats filter-paralogs`, please also cite minimap2, which performs the +genome alignments: + +``` +Li, H. (2018). Minimap2: pairwise alignment for nucleotide sequences. +Bioinformatics 34(18):3094-3100. https://doi.org/10.1093/bioinformatics/bty191 + +Li, H. (2021). New strategies to improve minimap2 alignment accuracy. +Bioinformatics 37(23):4572-4574. https://doi.org/10.1093/bioinformatics/btab705 +``` + ## Example Acknowledgment In your methods section: > Microhaplotype read counts were generated from the demultiplexed FASTQ files with MADCATS -> v0.13.0 (Sandercock, 2026), using panel tags reconstructed from the vendor design files and +> v0.14.0 (Sandercock, 2026), using panel tags reconstructed from the vendor design files and > default evidence and denoising settings. diff --git a/docs/src/commands/design.md b/docs/src/commands/design.md index 68f7141..efb7921 100644 --- a/docs/src/commands/design.md +++ b/docs/src/commands/design.md @@ -10,23 +10,24 @@ madcats design --primers --probe-design --output [OPTIONS] ## Description -`design` turns a vendor's primer-sequence CSV and bracket-notation probe-design file into a -platform-neutral reference-tag CSV. It uses no sequencing data and gives the same result every -time. The other panel routes were validated against it. +`design` converts a vendor primer-sequence CSV and bracket-notation probe-design file into a +platform-neutral reference-tag CSV. Because it uses no sequencing data and runs deterministically, +it serves as the ground-truth reference when checking other panel construction routes. -For each marker it: +For each marker, `design`: -1. locates the left primer inside the probe-design target, in either orientation; -2. keeps only primer-started tag windows that contain the bracketed variant (a primer occurrence - in a duplicated flank that never reaches the variant is not a candidate); -3. builds the Ref and Alt tags as the primer sequence verbatim plus the genomic continuation, so - degenerate (IUPAC) primer bases persist exactly as the vendor reports them; -4. checks the result and stops with an error if the files disagree. +1. Locates the left primer inside the probe-design target sequence on either strand. +2. Retains only primer-started tag windows that span the bracketed variant (ignoring primer matches + in duplicated flanking regions that do not reach the variant). +3. Builds the Ref and Alt tags from the verbatim primer sequence followed by the genomic + continuation, preserving any degenerate (IUPAC) primer bases exactly as reported by the vendor. +4. Validates consistency between the primer table and probe design and stops with an error if they + disagree. -SNPs, insertions, deletions and homopolymer-shifted indels are handled by one rule: the variant -position is where the two full allele expansions first differ. +The same logic handles SNPs, insertions, deletions, and homopolymer-shifted indels, defining the +variant position as the first base where the full Ref and Alt expansions differ. -> **When to use:** whenever you have both design files. `generate` can also read them directly +> **When to use.** Use it whenever you have both design files. `generate` can also read them directly > (`--primers` + `--probe-design`), but running `design` first gives you a reviewable panel you > can reuse without the vendor files. @@ -67,9 +68,9 @@ madcats design \ ## Output Format -A reference-tag CSV with one row per marker; see -[Input Formats](../getting-started/input-formats.md#reference-tags-csv). The number of definitions -written is printed to stderr. +A reference-tag CSV with one row per marker. See +[Input Formats](../getting-started/input-formats.md#reference-tags-csv). The command prints the +number of definitions it wrote to stderr. ## Errors @@ -83,11 +84,11 @@ The run stops, naming the marker, when: | Panel | Design tags vs vendor canonical rows | |-------|--------------------------------------| -| Blackberry (3,015 markers, 10 indels) | 2,881 identical; all 134 others differ only by vendor IUPAC codes | -| Pecan 3K | 3,084 identical of 3,100; 16 differ only by vendor IUPAC codes | +| Blackberry (3,015 markers, 10 indels) | 2,881 identical, and all 134 others differ only by vendor IUPAC codes | +| Pecan 3K | 3,084 of 3,100 identical, and 16 differ only by vendor IUPAC codes | | Sweetpotato | All 6,238 81-bp prefixes of the public PanelHub 109-bp design sequences agree | ## See Also -- [madcats infer-design](infer-design.md): the same panel without the primer file -- [madcats generate](generate.md): use the panel +- [madcats infer-design](infer-design.md) for the same panel without the primer file +- [madcats generate](generate.md) to use the panel diff --git a/docs/src/commands/filter-paralogs.md b/docs/src/commands/filter-paralogs.md new file mode 100644 index 0000000..1bf28da --- /dev/null +++ b/docs/src/commands/filter-paralogs.md @@ -0,0 +1,272 @@ +# madcats filter-paralogs + +Drop or flag MADC haplotypes that a reference genome places at another locus. This command is +optional, marked **experimental** in 0.14.0 (so its options, defaults, and outputs may change), and +requires the `mappy` aligner (`pip install 'madcats[genome]'`). + +## Synopsis + +```bash +madcats filter-paralogs --madc --genome [--genome-index ] --output [OPTIONS] +madcats filter-paralogs --madc --genome-index --output [OPTIONS] +``` + +## Description + +In some targeted genotyping panels, paralogous copies of a target locus co-amplify and contribute +reads to the marker's rows. A paralogous haplotype that matches the target base at the variant +position becomes a RefMatch or AltMatch row. When downstream tools sum read counts across all rows +at the target SNP (as `BIGr::madc2vcf_all` does), those paralogous reads push homozygous samples +toward false heterozygous genotype calls. `filter-paralogs` aligns each haplotype to a reference +genome to identify where it originates: + +1. **Locate each marker.** `filter-paralogs` aligns each marker's Ref tag to the reference genome. + For `CHROM_POS` CloneIDs (zero-padding allowed, e.g., `Chr1_000333995`), it uses that coordinate + as the marker's expected position on the genome. This coordinate breaks ties among multiple + equal-best hits, serves as a fallback when the Ref tag does not align, and can override a + higher-scoring off-target hit (see [CloneID Positions](#cloneid-positions)). If a marker has + multiple equal-best sites that the CloneID position cannot resolve, it is treated as multi-copy. +2. **Align every distinct haplotype.** Each haplotype receives two alignment scores: its best score + at the marker's target site and its best score anywhere else in the genome. `filter-paralogs` + also realigns each haplotype locally at its marker site using shorter seeds so genuine divergent + alleles with multiple SNPs still receive an accurate on-target score even if the genome-wide + search misses them. +3. **Assign a genome label:** + + | Label | Meaning | Default action | + |-------|---------|----------------| + | `on_target` | The marker's target site scores strictly higher than any off-target site | kept | + | `paralog` | An off-target site scores strictly higher, or the haplotype aligns only off-target | dropped (`--paralogs`) | + | `ambiguous` | The target site ties with an off-target site, or the marker's Ref tag is unresolved multi-copy | dropped (`--ambiguous`) | + | `unmapped` | Does not align anywhere in the reference genome | kept | + | `unplaced` | The marker itself could not be placed on the genome | kept | + +4. **Write the filtered MADC.** Canonical Ref and Alt rows are never dropped so downstream dosage + callers always receive both designed alleles. Any canonical row whose label would otherwise have + caused it to be dropped is recorded as `protected`. Kept rows are copied verbatim while + preserving the input file's layout (vendor starred preamble, statistics columns, HapApp's + `Code_version` column, and original column order). + +Use `filter-paralogs` on panels known to co-amplify paralogs, and inspect the fraction of `paralog` +reads in the QC JSON. On the lettuce 3K panel, paralogous rows accounted for 63% of all reads in the +vendor MADC, whereas on paralog-free panels the filter removes very few reads. + +`filter-paralogs` accepts raw MADCs from `generate`, vendor DArT MADCs, and HapApp fixed-allele-ID +MADCs (`Code_version`, `AlleleID`, `CloneID`, `AlleleSequence`, followed by sample columns with IDs +such as `|Ref_0001`), so you can run it either before or after HapApp. + +Alignment scores follow minimap2's short-read scoring (match +2, mismatch −8, gap open −12, gap +extension −2, ambiguous base −1) and are recomputed directly from each alignment so score ties are +exact. + +## Required Arguments + +| Argument | Description | +|----------|-------------| +| `--madc ` | MADC to filter, plain or gzipped: from `generate`, a vendor DArT MADC (with or without its starred preamble), or a HapApp fixed-allele-ID MADC | +| `--output ` | Filtered MADC to write (must differ from `--madc`) | + +Give `--genome`, `--genome-index`, or both. + +## Genome + +| Option | Default | Description | +|--------|---------|-------------| +| `--genome ` | none | Reference genome FASTA, optionally gzipped | +| `--genome-index ` | none | minimap2 index. The command loads it when it exists, and otherwise builds it from `--genome` and saves it here for the next run | +| `--clone-positions {use,ignore}` | `use` | `use` reads `CHROM_POS` CloneIDs as positions on the genome given (see [CloneID Positions](#cloneid-positions)). `ignore` them when they refer to another assembly | + +Indexing a large genome is slow and needs memory: the 2.4 Gb lettuce genome took 50 s and 10.6 GB, +for a 5.7 GB index. Build the index once and reuse it. The first run with both options writes it: + +```bash +madcats filter-paralogs --madc MADC.csv --genome genome.fa --genome-index genome.sr.mmi --output MADC_filtered.csv +``` + +Later runs need only `--genome-index`. An index from the minimap2 command line works too, if it +is in one part. Build it with the short-read preset and `-I` above the genome size: + +```bash +minimap2 -x sr -I 20G -d genome.sr.mmi genome.fa +``` + +minimap2 splits the index of a genome larger than `-I` (8 Gb by default), and mappy searches only +the first part, so the command refuses a multi-part index. An index the command builds itself is +always one part. + +The genome should hold each locus once. If the assembly is haplotype-resolved, or carries every +copy of each chromosome of an autopolyploid, index one set of chromosomes only (see +[Limitations](#limitations)). + +## Options + +| Option | Default | Description | +|--------|---------|-------------| +| `--paralogs {drop,flag}` | `drop` | Drop `paralog` rows, or keep them labeled in the `GenomeLabel` column | +| `--ambiguous {drop,flag,keep}` | `drop` | Drop, flag, or keep `ambiguous` rows. Kept rows still carry their label when `--paralogs flag` enables the `GenomeLabel` column | +| `--qc-output ` | `OUTPUT.qc.json` | QC JSON path | +| `--jobs ` | up to 4 | Number of alignment threads | + +By default, ambiguous rows are dropped. On the lettuce dataset, keeping ambiguous rows increased +false heterozygous calls in inbred lines from 0.87% to 3.4%. + +## Flag Mode + +When either `--paralogs` or `--ambiguous` is set to `flag`, `filter-paralogs` renames the `PICRef` +column to `GenomeLabel`, writes every row's label there (`on_target`, `paralog`, `ambiguous`, +`unmapped`, or `unplaced`), and keeps flagged rows. Because column positions do not shift, +positional consumers still see the standard 16-column layout (in vendor MADCs, this overwrites the +vendor's `PICRef` statistic). HapApp's fixed-allele-ID format does not contain a `PICRef` column, so +use drop mode and inspect the labels sidecar when filtering HapApp tables. + +Flagged files are intended for inspection. Tools that validate exact vendor column headers (such as +HapApp-online's upload checker) reject `GenomeLabel` in place of `PICRef`, so pass drop-mode output +to those tools. + +## Outputs + +| File | Contents | +|------|----------| +| `OUTPUT` | The filtered MADC | +| `OUTPUT.genome_labels.csv` | One line per haplotype row, dropped rows included. A row with an empty `AlleleID` is not a haplotype row, and the filter leaves it out of both files | +| `OUTPUT.genome_markers.csv` | One line per marker, recording where and how the filter placed it | +| `OUTPUT.qc.json` | Parameters, aligner settings, marker placement, haplotypes and reads per label, outcome and allele category, alignment time, and `count_overflow` (see below) | + +The filter sums read totals as stored. If the input has negative counts, the command warns and +`count_overflow` records how many cells and markers carry them. A negative count with a maximum of +127 points to signed 8-bit overflow in a vendor file. See the +[FAQ](../reference/faq.md#my-vendor-madc-has-negative-read-counts). + +When the input carries a MADCATS provenance cell (`generate --dart-preamble`), the filter appends +its settings to it. + +### Labels sidecar + +| Column | Contents | +|--------|----------| +| `CloneID`, `AlleleID`, `AlleleSequence` | Row identity | +| `Label` | `on_target`, `paralog`, `ambiguous`, `unmapped` or `unplaced` | +| `Action` | `kept`, `flagged`, `dropped`, or `protected` (a canonical row kept despite its label) | +| `TargetScore` | Best alignment score at the marker's site (`.` if none) | +| `TargetFrom` | `genome` (the genome-wide search's hit at the site), `site` (the realignment at the marker's site, when it scored higher or the genome-wide search found nothing there) or `.` | +| `OffTargetScore` | Best alignment score anywhere else (`.` if none) | +| `OffTargetSites` | Distinct sites elsewhere at that score, among the 8 sites kept for a haplotype | +| `OffTargetHit` | The best site elsewhere, 1-based, such as `Chr4:61708465-61708545(+)` | + +A perfect 81-base match scores 162 and each mismatch costs 10, so `TargetScore` and +`OffTargetScore` show how many mismatches separate a haplotype from each copy. + +### Markers sidecar + +| Column | Contents | +|--------|----------| +| `CloneID` | Marker | +| `Placement` | `ref_tag`, `ref_tag+clone_id` (multi-copy Ref tag resolved by the CloneID position), `ref_tag_multicopy` (unresolved), `clone_id_site` (the Ref tag's alignment at the CloneID position, though it aligns better elsewhere), `clone_id` (Ref tag did not align) or `unplaced` | +| `RefTagSites` | Equal-best genome sites of the Ref tag (0 when it did not align). The genome-wide search returns at most 51 hits, so this counts the sites found, not necessarily every copy | +| `CloneIDCheck` | `agree`, `disagree`, `no_position` (CloneID is not `CHROM_POS`), `contig_absent`, `fallback` or `ignored` (`--clone-positions ignore`) | +| `Sites` | The marker's site(s), 1-based, `;`-separated | + +## CloneID Positions + +With `--clone-positions use` (default), `filter-paralogs` interprets `CHROM_POS` CloneIDs as the +marker's expected coordinates on the provided design assembly. If the Ref tag fails to align, a +window around that coordinate becomes the marker's target site (`clone_id`). If none of the Ref +tag's equal-best genome hits matches the CloneID coordinate (`CloneIDCheck` `disagree`), the command +realigns the Ref tag locally within that window. If it aligns there, that local alignment becomes +the marker's target site (`clone_id_site`) even if an off-target paralog scored higher genome-wide +(for example, when the assembly carries the Alt allele at the target while a paralog carries the Ref +allele). If the Ref tag still fails to align in that window, the marker is marked `unplaced` and all +of its rows are kept. + +If more than 10% of markers disagree with their CloneID positions, `filter-paralogs` prints a +warning because either the wrong genome was provided or the CloneIDs correspond to a different +assembly. In that case, rerun with `--clone-positions ignore`. + +## Using Another Assembly + +Because `filter-paralogs` locates markers by aligning their Ref tags, you can run it against any +reference genome containing the panel's target loci, not only the design assembly. Comparing labels +across two assemblies (such as different cultivars) highlights haplotypes supported differently by +each genome. A haplotype labeled `on_target` against one genome and `paralog` against another aligns +better to an off-target locus in the second genome. Because that difference may reflect either an +extra paralog copy or sequence divergence in a shared copy, confirm structural differences directly +in the assemblies. + +Because CloneID coordinates belong to the design assembly, pass `--clone-positions ignore` when +aligning to a different assembly. Otherwise, matching chromosome names will cause `filter-paralogs` +to look up old coordinates on the new genome and misplace markers. Under `ignore`, a marker whose +Ref tag fails to align is labeled `unplaced` (keeping all rows), and a Ref tag with multiple +equal-best hits stays multi-copy (labeling its rows `ambiguous`). Keep the default `use` on the +design assembly, where CloneID coordinates resolved 11 of 2,987 markers on the lettuce vendor MADC. + +Each genome needs its own index: + +```bash +madcats filter-paralogs --madc MADC.csv --genome-index v8.sr.mmi --output MADC_v8.csv +madcats filter-paralogs --madc MADC.csv --genome other.fa --genome-index other.sr.mmi \ + --clone-positions ignore --output MADC_other.csv +``` + +To compare the two runs, join their labels sidecars on `CloneID` and `AlleleSequence`: + +```python +import pandas as pd + +key = ["CloneID", "AlleleSequence"] +design = pd.read_csv("MADC_v8.csv.genome_labels.csv") +other = pd.read_csv("MADC_other.csv.genome_labels.csv") +both = design.merge(other, on=key, suffixes=("_v8", "_other")) +print(pd.crosstab(both.Label_v8, both.Label_other)) +``` + +## Example + +```bash +madcats filter-paralogs \ + --madc DLet22-7611_MADC.csv \ + --genome-index ref/Lsativa_467_v8_Chr.sr.mmi \ + --output DLet22-7611_MADC_filtered.csv \ + --jobs 8 +``` + +On the lettuce 3K DArT MADC (732,534 rows, 376 samples) this took 2 min 15 s and 9.4 GB of memory. +It kept 113,667 rows, with 35.7% of the reads. See the +[paralog filter tutorial](../tutorials/paralog-filter.md) for the whole workflow. + +## Limitations + +- The reference genome must contain the panel's target loci, so use the design assembly or a closely + related genome. `filter-paralogs` cannot evaluate markers whose genomic region is missing or + collapsed in the assembly. +- Paralogous copies present in your germplasm but absent from the reference assembly cannot be + detected and will look like diverged on-target alleles. Running against a second assembly that + contains the copy can reveal them (see [Using Another Assembly](#using-another-assembly)). +- minimap2 detects fewer highly diverged copies than bwa-mem, so `filter-paralogs` retains a small + fraction of distant rows that bwa-mem would drop (accounting for 1.0% of kept reads on the lettuce + vendor MADC). +- Alignment uses only the MADC tag sequence (81 bp by default) rather than the full sequencing read. +- A true allele that is equidistant from the target locus and a paralogous copy is labeled + `ambiguous`. +- Index only a single chromosome set (haploid representation). Providing a haplotype-resolved + assembly or all chromosome copies of an autopolyploid causes genuine alleles on alternate + haplotypes to be labeled `paralog` and shared alleles to be labeled `ambiguous`, even when CloneID + positions are used. On alfalfa, adding a second chromosome set increased dropped RefMatch and + AltMatch rows from 296 to 1,969 out of 2,753. +- When aligning to a different cultivar's genome with `--clone-positions ignore`, some Ref tags may + match a paralogous copy better than their true locus or fail to place, leaving those markers + misplaced or `unplaced` (with all rows retained). + +## Validation + +[Validation & Accuracy](../reference/validation.md#genome-paralog-filter-filter-paralogs) compares +`filter-paralogs` against bwa-mem and blastn on lettuce, alfalfa, and delta smelt datasets, as well +as planted paralog copies and genetic segregation in biparental families. Full benchmarks are +recorded in the +[development record](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md). +Results are deterministic and do not depend on `--jobs`. + +## See Also + +- [Paralog filter tutorial](../tutorials/paralog-filter.md) +- [madcats generate](generate.md) +- [Output Formats](../reference/output-formats.md) diff --git a/docs/src/commands/generate.md b/docs/src/commands/generate.md index 7aef3b1..8d49cc7 100644 --- a/docs/src/commands/generate.md +++ b/docs/src/commands/generate.md @@ -11,26 +11,31 @@ madcats generate --fastq-dir --primers --probe-design --outp ## Description -Every workflow ends with `generate`. It runs in seven stages, and the option tables below are -grouped by stage: - -1. Load the panel from a reference-tag CSV (or build it from DArT design files) and find one FASTQ - per sample. -2. Assign each read to a marker by its left-primer/anchor prefix, keep the fixed-length tag, and - accept it if it reaches `--min-identity` to the marker's Ref or Alt tag. Reads that fail for - every marker get one more try with a gapped alignment under the same edit limit, so undesigned - indels are counted. Reads shorter than the tag are added to a full-length allele whose start - they match. Results are cached per sample. +Every MADCATS workflow finishes with `generate`. It runs in seven sequential stages matching the +option groups below: + +1. Load the panel definition from a reference-tag CSV (or construct it from DArT primer and + probe-design files) and discover one FASTQ file per sample. +2. Assign each read to its target locus using its left-primer or anchor prefix, extract the + fixed-length tag, and accept reads meeting `--min-identity` against the marker's canonical Ref or + Alt tag. Reads that fail the substitution-only check for all candidate markers receive one banded + gapped alignment under the same edit limit so undesigned indels are recovered. When a read + matches multiple tiled markers from the same amplicon, MADCATS credits it to each matching tile + and drops other ties as ambiguous. Reads shorter than the tag length are credited to a + full-length allele whose prefix they match unambiguously. For longer reads, MADCATS retains the + downstream bases following each tag for Stage 6 and caches per-sample results. 3. Count exact tag sequences per sample. -4. Apply the evidence rules. Canonical Ref and Alt rows are always written; any other sequence is - reported only if it passes an evidence route. -5. Denoise. Within each sample, rare sequences one edit away from a much more common one are merged - into it. A pooled pass then merges sequences that failed the evidence rules into a parent that - carries the same target allele. -6. Classify each row as Ref, Alt, RefMatch, AltMatch or Other, and annotate it. -7. Write the MADC, the QC/provenance JSON and the variants sidecar. - -The [Evidence Model](../reference/evidence-model.md) explains stages 2–6 in detail. +4. Evaluate the evidence rules. Canonical Ref and Alt rows are always reported, while novel + sequences are reported only if they pass at least one enabled evidence route. +5. Denoise counts. Within each sample, rare sequences within one substitution of a much more + abundant parent are absorbed into that parent. A pooled pass then merges evidence-failing + sequences into a protected or canonical parent carrying the same target allele. +6. Classify each row as Ref, Alt, RefMatch, AltMatch, or Other and annotate its variants against the + Ref tag. If a row's target falls in an unresolved end, MADCATS re-evaluates it using the + downstream bases that extend past the tag. +7. Write the MADC table, the QC/provenance JSON, and the variants sidecar CSV. + +See the [Evidence Model](../reference/evidence-model.md) for a detailed description of stages 2–6. > **Process a cohort in one invocation.** The reproducibility route counts supporting samples > within the run, so splitting a cohort into batches weakens discovery. `--cache-dir` makes @@ -42,7 +47,7 @@ The [Evidence Model](../reference/evidence-model.md) explains stages 2–6 in de |----------|-------------| | `--fastq-dir ` | Folder containing one FASTQ(.gz) per sample | | `--output ` | MADC CSV to write | -| `--reference-tags ` | Reference-tag CSV, **or** | +| `--reference-tags ` | Reference-tag CSV, or | | `--primers ` + `--probe-design ` | DArT design files | ## Panel and Samples (stage 1) @@ -52,52 +57,147 @@ The [Evidence Model](../reference/evidence-model.md) explains stages 2–6 in de | `--fastq-glob ` | `*` | FASTQ filename glob within `--fastq-dir` | | `--target-metadata ...` | `targets_*.csv` in the FASTQ folder | Target-manifest CSV(s) for sample metadata | | `--sample-name-field ` | targetid / FASTQ stem | Unique metadata field used for sample columns | -| `--sample-lookup ` | none | Two-column CSV/TSV mapping FASTQ-derived ids to sample names. Every run sample must be mapped | +| `--sample-lookup ` | none | Two-column CSV/TSV mapping FASTQ-derived ids to sample names. Every run sample needs an entry | | `--tag-length ` | 81 | Tag length | ## Read Assignment (stage 2) | Option | Default | Description | |--------|---------|-------------| -| `--min-identity ` | 0.80 | Minimum substitution-only identity to a Ref or Alt tag; a gapped alignment uses the same edit limit | -| `--leading-anchor ` | none | Constant sequence before the amplicon in raw deliveries (DArT: `GATGGATCCAGTGC`). Each read is cut where the anchor ends (it must end within 40 bases beyond its own length). `auto` detects it from the first FASTQ | -| `--primer-mismatches {0,1}` | 1 | Mismatches allowed while assigning a primer/anchor. With `0`, reads from Match haplotypes whose distinguishing SNP falls inside the anchor are lost | -| `--gapped-rescue {on,off}` | `on` | Give reads that fail substitution-only identity one gapped alignment, so undesigned indels are counted | -| `--max-indel-length ` | 10 | Widest gap (alignment band) a gapped alignment may use | -| `--partial-read-mode {on,off}` | `on` | Add a read shorter than the tag to the one full-length allele (already passing the evidence rules) whose start it matches, only when it is longer than every prefix shared between that locus's alleles. `off` drops such reads | -| `--min-partial-length ` | tag length − 9 | Minimum length of a credited partial read | -| `--cache-dir ` | none | Reusable per-sample count cache | -| `--jobs ` | up to 4 | Samples processed in parallel (also parallelizes denoising) | +| `--min-identity ` | 0.80 | Minimum substitution-only identity to the marker's Ref or Alt tag. Gapped rescue alignments use the same edit limit | +| `--leading-anchor ` | none | Constant sequence preceding the amplicon in raw deliveries (for DArT, `GATGGATCCAGTGC`). MADCATS cuts each read immediately after the anchor, which must end within 40 bp beyond the anchor's length. `auto` detects the prefix from up to 24 FASTQ files (with only one or two files, the detected prefix may include sample barcode bases and MADCATS prints a warning) | +| `--leading-anchor-mismatches {0,1}` | 0 | Substitutions allowed in the leading anchor. `0` requires an exact match (matching 0.13.0). With `1`, reads without an exact anchor match are cut after their unique one-substitution match and tallied as `reads_leading_anchor_mismatch`. Anchors shorter than 12 bp always require an exact match | +| `--primer-mismatches {0,1}` | 1 | Mismatches allowed when matching a read's start to a left primer or assignment anchor. Setting `0` drops reads from Match haplotypes that carry a SNP inside the primer or anchor | +| `--gapped-rescue {on,off}` | `on` | Rescue indel reads via gapped alignment and classify targets and `Variants` through accepted gaps. With `off`, indel rows are read at fixed offsets and may receive the wrong category (see [Classification](../reference/evidence-model.md#classification)) | +| `--max-indel-length ` | 10 | Maximum gap length (alignment band width) allowed during gapped alignment | +| `--tile-groups {auto,declared,off}` | `auto` | Credit reads matching multiple tiled markers from the same amplicon to each matching tile instead of dropping them as ambiguous ties. `auto` links declared `LocusGroup` tiles and detects undeclared tiles, `declared` links only declared groups, and `off` disables tile linking (see [Tiled Markers](../getting-started/input-formats.md#tiled-markers)) | +| `--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) | Option | Default | Description | |--------|---------|-------------| -| `--min-global-count ` | 1 | Minimum project-wide reads for a de novo allele | -| `--reproducible-min-reads ` | 10 | Reproducibility route: reads required per supporting sample | -| `--reproducible-min-samples ` | 2 | Reproducibility route: supporting samples required; `0` disables the route | -| `--depth-min-reads ` | 30 | Depth route: reads within one sample that establish an allele on their own; `0` disables | -| `--quality-min-clean-reads ` | 0 | Quality route: project-wide clean reads that establish an allele; `0` (default) disables | -| `--discovery-min-quality {10,20,30,40}` | 20 | Phred score every tag base must reach for a read to count as clean | -| `--min-supporting-freq ` | 0 | Minimum share of a sample's locus reads before that sample can support the reproducibility or depth route | +| `--min-global-count ` | 1 | Minimum total reads across the project required for a novel allele | +| `--reproducible-min-reads ` | 10 | Minimum reads per supporting sample for the reproducibility route | +| `--reproducible-min-samples ` | 2 | Minimum supporting samples required by the reproducibility route (`0` disables the route) | +| `--depth-min-reads ` | 30 | Reads within a single sample sufficient to establish a novel allele via the depth route (`0` disables) | +| `--quality-min-clean-reads ` | 0 | Project-wide clean reads required to establish a novel allele via the quality route (`0` disables) | +| `--discovery-min-quality {10,20,30,40}` | 20 | Minimum Phred score every tag base must meet for a read to count as clean | +| `--min-supporting-freq ` | 0 | Minimum fraction of a sample's locus reads required before that sample supports a sequence via the reproducibility or depth route | ## Denoising (stage 5) | Option | Default | Description | |--------|---------|-------------| -| `--denoise-distance {0,1,2}` | 1 | Per-sample denoising: the most differing bases allowed between a rare sequence and its parent; `0` disables | -| `--global-denoise-distance {0,1,2}` | 1 | Most differing bases allowed in the pooled same-allele merge; `0` disables | -| `--denoise-alpha ` | 2.0 | UNOISE-style abundance-skew exponent | +| `--denoise-distance {0,1,2}` | 1 | Maximum Hamming distance (in substitutions) between a rare sequence and its parent during per-sample denoising (`0` disables) | +| `--global-denoise-distance {0,1,2}` | 1 | Maximum Hamming distance allowed during the pooled same-allele merge (`0` disables) | +| `--denoise-alpha ` | 2.0 | UNOISE2 abundance-skew exponent | ## Output (stages 6–7) | Option | Default | Description | |--------|---------|-------------| -| `--qc-output ` | `OUTPUT.qc.json` | QC/provenance JSON | -| `--annotations {on,off}` | `on` | Repurpose `PICSnp` as `Variants` and `AvgPIC` as `MarkerType`, and write `OUTPUT.variants.csv`. `off` keeps the exact vendor header | -| `--number-match-ids` | off | Append stable per-file serials to Match IDs | -| `--dart-preamble` | off | Prepend the vendor-style seven-row starred preamble that HapApp expects | -| `--preamble-project ` | output name before its first dot | Label for the first preamble row | +| `--qc-output ` | `OUTPUT.qc.json` | Path for the QC/provenance JSON report | +| `--annotations {on,off}` | `on` | Repurpose `PICSnp` as `Variants` and `AvgPIC` as `MarkerType`, and write `OUTPUT.variants.csv`. `off` restores the exact vendor header and omits the sidecar | +| `--remove-primers {on,off}` | `off` | Trim primer sequences from emitted rows and sum counts for rows that become identical (requires `--annotations on`, see [Removing Primers](#removing-primers)) | +| `--number-match-ids` | off | Append stable per-file serial numbers to Match and Other `AlleleID`s | +| `--dart-preamble` | off | Prepend the seven vendor-style starred preamble rows expected by HapApp | +| `--preamble-project ` | output name before its first dot | Project or service label written in the first preamble row | + +## Removing Primers + +By default, each row's `AlleleSequence` contains the full tag as sequenced, starting with the left +primer. When the amplicon is shorter than the tag length plus the right primer, the tag also ends +with leading bases of the right primer. Because primer bases come from the assay oligos rather than +biological variation in the sample, `--remove-primers on` removes them before writing the table: + +- **Left primer.** MADCATS strips the exact length of `LeftPrimerSequence` from the start of every + row. Because read assignment does not allow indels inside the left primer, this boundary is exact. +- **Right primer.** `generate` infers the right-primer start position directly from the panel + definition. On platforms with a uniform amplicon length (such as DArTag), tags that reach the + right primer share a consistent amplicon length. Because an upstream indel shifts where the right + primer begins, MADCATS cuts each row where its alignment to the Ref tag reaches the right primer, + so trimmed rows at the same marker can differ in length. +- **Merged rows.** Rows within the same allele group that become identical after primer removal are + merged into a single row with summed read counts. Most merged pairs differed only within a primer + region. +- **Annotations.** `ClusterConsensusSequence`, `Variants`, `MarkerType`, and the variants sidecar + all reflect the trimmed sequences, with 1-based positions starting at the first base after the + left primer. + +Primer removal applies only when writing the output table. Read assignment, counting, denoising, +and allele classification still run on the full tags exactly as with `--remove-primers off`. No +reads are gained or lost, and no reads move between target allele groups. + +Important considerations before enabling `--remove-primers on`: + +- **The panel must contain physical primer sequences.** In panels built by `infer-design`, + `normalize-reads`, or from a vendor MADC, `LeftPrimerSequence` is an assignment anchor whose + length may differ from the physical primer. Enabling primer removal on those panels strips the + anchor instead, so use `--remove-primers on` only with panels built from a physical primer file + (`design`, or `generate --primers --probe-design`). +- **The right primer is trimmed only where detected.** The QC JSON reports the inferred amplicon + length and per-marker outcomes under `primer_removal`. If a panel lacks a uniform amplicon length + or its tags end before the right primer, rows lose their right primer only when a short product + brings either the full right primer or at least its first 10 bp into the tag. +- **Right-primer cuts are estimates.** Evaluated against full-length reads on pecan and sweetpotato + DArTag cohorts, 99.4% and 99.2% of reads belonged to rows cut at the exact primer boundary. Rare + misplaced cuts are usually caused by an indel within ~5 bp of the right primer, which appears as + substitutions in a fixed-length tag. +- **Protective retention rules.** A row keeps its right primer whenever trimming would remove the + base used to classify its target allele (even if that base overlaps the primer) or leave fewer + than 10 bp. Rows with an unread target have no target base to protect and are trimmed wherever + their right primer is found. The QC JSON tracks these counts, and `rows_right_primer_removed` + includes canonical Ref and Alt rows even at markers with zero reads. +- **Rows from different allele groups are never merged.** If trimming the right primer would make + rows from different allele groups (Ref/RefMatch, Alt/AltMatch, or Other) identical, non-canonical + 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: + passing a primer-trimmed table to a database built from untrimmed tables causes HapApp to assign + brand-new fixed IDs for every allele while carrying over untrimmed Ref and Alt sequences. Keep one + consistent setting across all projects that share a HapApp database. +- **Requires `--annotations on`.** Because `Variants` records how each trimmed row was aligned and + classified, `generate` stops with an error if `--remove-primers on` is combined with + `--annotations off`. Downstream steps that drop annotation columns (such as HapApp's + fixed-allele-ID table) discard that record, so retain the original MADC and its variants sidecar. +- **Downstream variable-length compatibility.** `BIGr::madc2vcf_targets` and `BIGr::madc2vcf_all` + successfully processed a primer-trimmed pecan table in HapApp's fixed-allele-ID format, whereas + `BIGr::madc2vcf_multi` did not produce a VCF because polyRAD truncates every row at a marker to + the shortest row's length. `filter-paralogs` has not yet been evaluated on primer-trimmed tables, + where shorter sequences are harder to place uniquely on a reference genome. + +## Output Differences From 0.13.0 + +Running with `--tile-groups off` restores the 0.13.0 read-assignment behavior. However, three +classification and annotation improvements are always active in 0.14.0: + +- **Unresolved ends and read continuation.** Rows whose trailing bases have a cheaper but unverified + gapped alignment are now marked `unresolved` (and classified as `Other` if the target falls in the + unresolved region), unless downstream bases past the tag settle the alignment. This affects + 2.2–3.2% of rows across the four benchmark cohorts (see + [Classification](../reference/evidence-model.md#classification)). Because pooled denoising groups + rows by target allele category, a small number of adjacent rows can also shift counts slightly. +- **Fewer-gap tie-breaking.** When gapped alignments to the Ref and Alt tags have identical edit + distances, MADCATS now selects the alignment with fewer separate gaps. This reclassifies + 0.03–0.10% of rows from `RefMatch` or `Other` to `AltMatch`. +- **Alt-derived variant annotations.** Rows classified from the Alt tag alignment now report their + `Variants` directly from that alignment (in Ref tag coordinates) so the category and variant + annotations always agree on the target base. + +The provenance header and QC JSON metadata fields also reflect the 0.14.0 format. ## Examples @@ -144,20 +244,23 @@ madcats generate ... --reproducible-min-reads 20 ### Exhaustive discovery -Setting every route's threshold to 0 emits every sequence with at least `--min-global-count` reads: +With every route disabled, `generate` writes every sequence with at least `--min-global-count` +reads: ```bash -madcats generate ... --reproducible-min-reads 0 --depth-min-reads 0 --quality-min-clean-reads 0 +madcats generate ... --reproducible-min-samples 0 --depth-min-reads 0 --quality-min-clean-reads 0 ``` ## Output | File | Contents | |------|----------| -| `OUTPUT` | MADC table; see [Output Formats](../reference/output-formats.md) | +| `OUTPUT` | MADC table, described in [Output Formats](../reference/output-formats.md) | | `OUTPUT.qc.json` | Parameters, provenance, per-sample read accounting | | `OUTPUT.variants.csv` | One variant event per line (`--annotations on`) | +With `--remove-primers on`, all three describe the rows without their primers. + `OUTPUT.qc.json` and `OUTPUT.variants.csv` append to the full output name, so `--output MADC.csv` writes `MADC.csv.qc.json` and `MADC.csv.variants.csv`. diff --git a/docs/src/commands/infer-design.md b/docs/src/commands/infer-design.md index 2e3eb67..bea7486 100644 --- a/docs/src/commands/infer-design.md +++ b/docs/src/commands/infer-design.md @@ -11,22 +11,23 @@ madcats infer-design --probe-design --fastq-dir --output [OP ## Description -The tag must be a tag-length window of the bracket-expanded target that contains the variant. So -inference only has to choose among a fixed set of candidate windows (every such window, on both -strands); it never assembles new sequences. Reads vote for windows in two tiers, in order: - -1. The exact tier counts reads whose prefix exactly matches a candidate window. When a locus has any - exact votes, they decide. -2. The fuzzy tier runs only for loci with no exact votes. It accepts reads that pass the - `--min-identity` rule, and tags already resolved for other loci compete for those reads too, so - one locus's reads are not counted for another. - -A locus is resolved when its winning window has at least `--dominance-ratio` times the runner-up's -votes. The `LeftPrimerSequence` written to the CSV is the shortest tag prefix that is unique in the -panel (between `--anchor-min-length` and `--anchor-max-length`, and always ending before the -variant). Loci that cannot be resolved are left out, and the QC report gives the reason for each. - -See [Panels Without a Primer File](../tutorials/primer-free.md) for a walkthrough and accuracy +Because a valid tag must be a tag-length window of the bracket-expanded target containing the +variant, `infer-design` selects from that finite set of candidate windows across both strands rather +than assembling sequences de novo. Reads vote for candidate windows in two tiers: + +1. **Exact tier:** Counts reads whose prefix exactly matches a candidate window. Whenever a locus + receives exact votes, they determine the winner. +2. **Fuzzy tier:** Runs only for loci with no exact votes. It accepts reads passing the + `--min-identity` threshold, allowing already-resolved tags from other loci to compete for those + reads so one locus cannot capture another locus's reads. + +A locus is resolved when its top window has at least `--dominance-ratio` times as many votes as the +runner-up. The `LeftPrimerSequence` column records the shortest tag prefix that uniquely identifies +the locus across the panel (between `--anchor-min-length` and `--anchor-max-length`, always ending +before the variant). Unresolved loci are excluded from the output CSV and logged with their reasons +in the QC JSON report. + +See [Panels Without a Primer File](../tutorials/primer-free.md) for a tutorial and accuracy figures. ## Required Arguments @@ -42,14 +43,14 @@ figures. | Option | Default | Description | |--------|---------|-------------| | `--fastq-glob ` | `*` | FASTQ filename glob within `--fastq-dir` | -| `--leading-anchor ` | none | Constant sequence preceding the amplicon in raw deliveries, or `auto` to detect it. Reads without it do not vote | -| `--tag-length ` | 81 | Reported tag length of the panel (e.g. 54, 81, 109) | +| `--leading-anchor ` | none | Constant sequence before the amplicon in raw deliveries, or `auto` to detect it. Reads without an exact copy do not vote | +| `--tag-length ` | 81 | Tag length of the panel (e.g. 54, 81, 109) | | `--min-identity ` | 0.80 | Minimum identity for fuzzy-tier votes, as in `generate` | | `--dominance-ratio ` | 10 | A winning window needs at least this many times the runner-up's votes | -| `--fuzzy-min-reads ` | 30 | Fuzzy-tier votes needed to resolve a locus with no exact votes; `0` disables the fuzzy tier | +| `--fuzzy-min-reads ` | 30 | Fuzzy-tier votes needed to resolve a locus with no exact votes. `0` disables the fuzzy tier | | `--fuzzy-min-samples ` | 2 | Distinct samples that must contribute fuzzy votes | | `--anchor-min-length ` | 15 | Shortest pseudo-primer anchor to try | -| `--anchor-max-length ` | 30 | Longest pseudo-primer anchor; also capped below each variant | +| `--anchor-max-length ` | 30 | Longest pseudo-primer anchor, also capped below each variant | | `--jobs ` | up to 4 | Samples processed in parallel | | `--report ` | `OUTPUT.qc.json` | Inference QC JSON | @@ -88,12 +89,12 @@ madcats infer-design \ ## Output -- `OUTPUT`: the reference-tag CSV, with one row per resolved locus. -- `OUTPUT.qc.json` (for example `inferred_reference_tags.csv.qc.json`): each locus's route - (exact or fuzzy), support, margin, anchor length and flags, plus every excluded marker and the - reason (no bracketed variant, flanks too short for the tag length, no reads within identity, - support below threshold, ambiguous windows). Markers sharing a sequence-identical candidate - window carry a paralog review flag. +- `OUTPUT` is the reference-tag CSV, with one row per resolved locus. +- `OUTPUT.qc.json` (for example `inferred_reference_tags.csv.qc.json`) records each locus's route + (exact or fuzzy), support, margin, anchor length and flags. It also lists every excluded marker + and the reason: no bracketed variant, flanks too short for the tag length, no reads within + identity, support below threshold, or ambiguous windows. Markers sharing a sequence-identical + candidate window carry a paralog review flag. ## Tips @@ -104,5 +105,5 @@ madcats infer-design \ ## See Also -- [madcats design](design.md): use this instead when you have the primer file +- [madcats design](design.md) instead, when you have the primer file - [Panels Without a Primer File](../tutorials/primer-free.md) diff --git a/docs/src/commands/merge-pairs.md b/docs/src/commands/merge-pairs.md index c66c298..2124e9d 100644 --- a/docs/src/commands/merge-pairs.md +++ b/docs/src/commands/merge-pairs.md @@ -10,24 +10,29 @@ madcats merge-pairs --fastq-dir --out-dir [OPTIONS] ## Description -For assays whose inserts are shorter than R1 + R2, `merge-pairs` collapses each pair into one -fragment before `normalize-reads` or `generate`: - -- R2 is reverse-complemented and overlaps are scanned longest first. -- The merged read is R1's head, plus the overlap, plus R2's tail. In extended geometry that is the - whole fragment. In engulfed (read-through) geometry, R1's adapter tail past the fragment end lies - outside the overlap and never reaches the merged read, so no adapter trimming is needed. R2 - bases past R1's end are kept when the reads differ in length. -- Where overlap bases disagree, the higher-quality call wins. -- Mates are paired by read ID. Mismatched names or unequal read counts stop the run with an error. - -Samples are independent and merge in parallel with `--jobs`. Each sample is written to -`OUT_DIR/.fastq.gz`, where `` is the filename with the mate suffix removed. - -> **When to use:** only when mates overlap. For dual-anchored capture designs whose mates cover -> opposite halves of the fragment, pool both mates instead (see -> [Paired-End Reads and Tiling](../tutorials/paired-end.md)). MADCATS does not decide this -> for you. +For assays whose target fragments are shorter than the combined length of R1 and R2, `merge-pairs` +merges overlapping paired-end reads into single consensus fragments before running +`normalize-reads` or `generate`: + +- Reverse-complements R2 and evaluates candidate overlaps from longest to shortest. +- Constructs the merged read from R1's leading bases, the overlap region, and R2's trailing bases. + In extended geometry, this reconstructs the complete insert. In read-through (engulfed) geometry, + adapter bases extending past the amplicon fall outside the overlap and are trimmed automatically, + eliminating the need for separate adapter trimming. When R1 and R2 differ in length, the merged + read retains R2 bases extending past the end of R1. +- Resolves any base-call disagreements within the overlap by selecting the base with the higher + Phred quality score. +- Verifies that mate pairs share matching read IDs and stops with an error if read names or counts + do not match. + +Samples are processed independently in parallel using `--jobs`. Each sample is written to +`OUT_DIR/.fastq.gz`, where `` is the filename stem with the mate suffix stripped. + +> **When to use.** Use `merge-pairs` when mates overlap (or pass `--unmerged pool` for mixed +> libraries where some pairs overlap and others do not). For strictly non-overlapping dual-anchored +> capture pairs whose mates cover opposite halves of a fragment, concatenate both mates per sample +> directly before `normalize-reads` (see [Paired-End Reads and Tiling](../tutorials/paired-end.md)). +> MADCATS does not auto-detect paired-end geometry. ## Required Arguments @@ -44,7 +49,8 @@ Samples are independent and merge in parallel with `--jobs`. Each sample is writ | `--r2-suffix ` | `_R2.fastq.gz` | Filename suffix of the R2 mate | | `--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` | Unmergeable pairs: `r1` keeps the R1, `pool` keeps both mates, `drop` discards the pair | +| `--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 @@ -70,12 +76,12 @@ madcats merge-pairs \ ## Accuracy -- Synthetic truth set with modeled adapter read-through: 100% of 513,715 pairs merged, 98.6% - molecular count recovery, zero length errors. -- Compared with FLASH 1.2.11, vsearch and fastp on a four-regime exact-truth set: equal to the best +- On a synthetic truth set with modeled adapter read-through, 100% of 513,715 pairs merged, with + 98.6% molecular count recovery and zero length errors. +- Compared with FLASH 1.2.11, vsearch and fastp on a four-regime exact-truth set, it matched the best (vsearch) in every regime, with zero false merges. ## See Also -- [madcats normalize-reads](normalize-reads.md): the usual next step +- [madcats normalize-reads](normalize-reads.md), the usual next step - [Paired-End Reads and Tiling](../tutorials/paired-end.md) diff --git a/docs/src/commands/normalize-reads.md b/docs/src/commands/normalize-reads.md index 6e10f31..179e97b 100644 --- a/docs/src/commands/normalize-reads.md +++ b/docs/src/commands/normalize-reads.md @@ -11,25 +11,26 @@ madcats normalize-reads --probe-design --fastq-dir --out-dir ## Description -`generate` expects every read to start at a fixed anchor. Platforms such as AgriSeq (Ion Torrent) -sequence amplicons from both ends with scattered start positions. `normalize-reads` adapts them: +Because `generate` expects every read to start at a fixed anchor, platforms such as AgriSeq (Ion +Torrent) and Flex-Seq require normalization before counting. `normalize-reads` converts +bidirectional or variable-start reads into fixed-length windows: -1. Each read is located against the probe-design targets by k-mer (`--kmer-size`) and oriented - forward. -2. A fixed-length window (`--tag-length`) containing the variant is excised. -3. Per-sample FASTQs of excised windows are written to `--out-dir`, together with the matching - window reference-tags CSV and a QC report. +1. Builds a k-mer lookup table (`--kmer-size`) from the probe-design targets, locates each read to + its candidate locus, and re-orients it to the forward strand. +2. Excises a fixed-length window (`--tag-length`) surrounding the target variant. +3. Writes one normalized FASTQ per sample to `--out-dir` along with a matching window + reference-tags CSV and QC report. -`generate` then runs unchanged on the output. +Once normalized, reads conform to the standard geometry expected by `generate`. -Windows are placed from the reads, so a new run can place them differently. Every later run of the -same panel should therefore pass `--reuse-tags` with the first run's window CSV. That keeps -microhaplotype sequences comparable across runs. See -[AgriSeq and Other Non-Primer-Started Reads](../tutorials/agriseq.md). +Because `normalize-reads` learns window boundaries from read coverage, running it fresh on a new +batch can shift window placement across runs. For every subsequent run of the same panel, pass the +baseline panel CSV via `--reuse-tags` so microhaplotype sequences remain directly comparable across +batches (see [AgriSeq and Other Non-Primer-Started Reads](../tutorials/agriseq.md)). -Markers that share a physical locus (`LocusGroup` in the probe design) are tiles. Reads are located -to the group as a whole, then routed among member windows by `--group-routing`, and fresh placement -forces member windows to excise distinct sequences. +Markers that share a `LocusGroup` in the probe design represent tiles of the same physical locus. +`normalize-reads` locates reads to the group as a whole and uses `--group-routing` to assign each +read to one or more member windows, ensuring distinct window sequences during fresh placement. ## Required Arguments @@ -45,11 +46,11 @@ forces member windows to excise distinct sequences. |--------|---------|-------------| | `--fastq-glob ` | `*` | FASTQ filename glob within `--fastq-dir` | | `--tag-length ` | 41 | Excised window length. Shorter windows lose fewer reads to indels on indel-prone chemistries | -| `--window-placement ` | `auto` | `auto` learns each marker's window from observed read coverage (an extra pass); `center` needs no read data. With `--reuse-tags`, `auto` scores the frozen windows instead and `center` skips that | -| `--anchor-length ` | 12 | Minimum assignment-anchor prefix length. Anchors grow per locus only where window prefixes collide; the variant is always kept out of the anchor | +| `--window-placement ` | `auto` | `auto` learns each marker's window from observed read coverage (an extra pass), while `center` needs no read data. With `--reuse-tags`, `auto` scores the frozen windows instead and `center` skips that | +| `--anchor-length ` | 12 | Minimum assignment-anchor prefix length. Anchors grow per locus only where window prefixes collide, and the anchor never includes the variant | | `--reuse-tags ` | none | Window reference-tags CSV from a previous run to reuse verbatim, freezing placement | -| `--group-routing ` | `nearest` | For reads covering several tiles of one `LocusGroup`: `nearest` feeds one tile, `covered` feeds every tile the read fully covers | -| `--str-penalty ` | 0.002 | Auto placement: coverage penalty per tandem-repeat bp (unit sizes 1–3) beyond 4 in a window; `0` disables | +| `--group-routing ` | `nearest` | For reads covering several tiles of one `LocusGroup`, `nearest` feeds one tile and `covered` feeds every tile the read fully covers | +| `--str-penalty ` | 0.002 | Auto-placement coverage penalty per tandem-repeat bp (unit sizes 1–3) beyond 4 in a window. `0` disables | | `--kmer-size ` | 21 | k-mer length for locating reads against the design targets | | `--jobs ` | up to 4 | Samples processed in parallel | | `--output-tags ` | `OUT_DIR/window_reference_tags.csv` | Window reference-tags CSV | @@ -100,14 +101,14 @@ madcats normalize-reads \ ## Tips 1. Pass the same `--tag-length` to `generate`. It must match the excised window length. -2. Use `--fastq-glob "*.fastq"` in `generate` so only normalized files are read. -3. With `--reuse-tags`, every row of the frozen panel is checked against the design. Rows that only - partly match, and panels that contain two identical windows, are rejected. +2. Use `--fastq-glob "*.fastq"` in `generate` so it reads only the normalized files. +3. With `--reuse-tags`, the command checks every row of the frozen panel against the design. It + rejects rows that only partly match, and panels that contain two identical windows. 4. With `--reuse-tags`, the QC (`freeze_health`) compares each frozen window's coverage on this run with the window fresh placement would pick, and lists markers that lose more than ten points. ## See Also -- [madcats window-scan](window-scan.md): choose `--tag-length` -- [madcats merge-pairs](merge-pairs.md): paired-end intake +- [madcats window-scan](window-scan.md) to choose `--tag-length` +- [madcats merge-pairs](merge-pairs.md) for paired-end intake - [AgriSeq tutorial](../tutorials/agriseq.md) diff --git a/docs/src/commands/overview.md b/docs/src/commands/overview.md index 6325513..54c30da 100644 --- a/docs/src/commands/overview.md +++ b/docs/src/commands/overview.md @@ -1,7 +1,6 @@ # Command Overview -MADCATS is a single executable with seven subcommands. Each handles one stage: defining the panel, -adapting reads, counting, or checking the result. +MADCATS commands define the panel, adapt reads, count alleles, filter paralogs and check the result. ## Command Structure @@ -37,7 +36,7 @@ Each produces the reference-tag CSV that `generate` consumes. | Command | Description | Primary Use | |---------|-------------|-------------| | [`merge-pairs`](merge-pairs.md) | Merge overlapping paired-end reads | GT-seq PE, rhAmpSeq | -| [`normalize-reads`](normalize-reads.md) | Orient and window non-primer-started reads; emits a window panel | AgriSeq, capture, merged amplicons | +| [`normalize-reads`](normalize-reads.md) | Orient and window non-primer-started reads, and emit a window panel | AgriSeq, capture, merged amplicons | | [`window-scan`](window-scan.md) | Recommend a window length from the project's reads | Before the first `normalize-reads` of a new panel | ### Counting and Checking Commands @@ -47,6 +46,12 @@ Each produces the reference-tag CSV that `generate` consumes. | [`generate`](generate.md) | Build the MADC count table | Every workflow ends here | | [`validate`](validate.md) | Compare a generated MADC with a reference MADC | Checking against a vendor delivery | +### Cleaning Command (Optional, Experimental) + +| Command | Description | Primary Use | +|---------|-------------|-------------| +| [`filter-paralogs`](filter-paralogs.md) | Drop or flag haplotypes that a reference genome places at another locus (experimental, requires `pip install 'madcats[genome]'`) | Panels where co-amplified paralogs inflate heterozygosity, supporting MADCATS, vendor, and HapApp fixed-ID MADCs | + ## Typical Workflows ### DArTag @@ -57,6 +62,13 @@ madcats generate --fastq-dir fastqs/ --reference-tags tags.csv --jobs 8 --output madcats validate --generated MADC.csv --expected vendor_MADC.csv --report validation.json ``` +### Paralog-heavy panel (optional genome filter) + +```bash +madcats generate --fastq-dir fastqs/ --reference-tags tags.csv --min-identity 0.95 --output MADC.csv +madcats filter-paralogs --madc MADC.csv --genome genome.fa --genome-index genome.sr.mmi --output MADC_filtered.csv +``` + ### AgriSeq ```bash @@ -81,19 +93,19 @@ These options appear on several commands: | `--fastq-glob` | Filename glob within `--fastq-dir` (default `*`) | | `--probe-design` | Probe/marker design TSV or CSV with bracketed variants | | `--tag-length` | Tag or window length in bases | -| `--jobs` | Samples processed in parallel (default: up to 4) | +| `--jobs` | Number of samples to process in parallel, up to 4 by default | | `--output` / `--out-dir` | Output file or folder | | `--report` / `--qc-output` | QC/provenance JSON path (each command has a default beside its output) | ## QC and Provenance -Every command that processes reads writes a JSON report recording its parameters, version, inputs -and read accounting, beside its main output. Keep it with the result, since it records exactly how -the table was made. +Every command that processes reads writes a JSON report beside its main output recording its +parameters, version, input paths, and read accounting. Keep this file alongside the output table as +a provenance record for the run. ## Exit Codes | Code | Meaning | |------|---------| | `0` | Success | -| `2` | Error: invalid arguments, missing or malformed input, or a design inconsistency (the message names the cause) | +| `2` | Error from invalid arguments, missing or malformed input, or a design inconsistency (the message names the cause) | diff --git a/docs/src/commands/validate.md b/docs/src/commands/validate.md index 5416a4b..60f1f7c 100644 --- a/docs/src/commands/validate.md +++ b/docs/src/commands/validate.md @@ -10,14 +10,16 @@ madcats validate --generated --expected [--report ] ## Description -`validate` measures how a generated table agrees with another MADC, typically the vendor's delivery -for the same FASTQs. It reports row precision and recall by allele category, classification -agreement on shared rows, and count agreement across shared row × sample cells. +`validate` compares a generated MADC table against a reference MADC (typically a vendor delivery +from the same FASTQ files). It calculates row precision and recall by allele category, +classification agreement across shared rows, and read-count correlation across shared row × sample +cells. -The reference MADC is used only for this comparison. It has no effect on `generate`. +The reference MADC is used strictly for post-hoc evaluation and has no role in `generate`. -Either file may carry the vendor's starred preamble rows; the header is located by its `AlleleID` -cell. +Both inputs may include vendor starred preamble rows. `validate` locates the header automatically +using the `AlleleID` column, even when another column precedes it (such as `Code_version` in +HapApp's fixed-allele-ID format). ## Required Arguments @@ -32,7 +34,7 @@ cell. |--------|---------|-------------| | `--report ` | none | Also write the JSON report to this file | -The report is always printed to stdout as JSON. +The command always prints the report to stdout as JSON. ## Example @@ -48,8 +50,9 @@ madcats validate \ | Section | Contents | |---------|----------| | `sample_overlap` | Samples in each file and in common | +| `count_overflow` | For each file, the negative count cells, the markers they fall in, and the minimum and maximum count. Negative counts with a maximum of 127 point to signed 8-bit overflow in a vendor file, and the command prints a warning | | `allele_rows` | Rows in common, precision, recall, generated-only and expected-only counts, `classification_agreement` on shared rows, category counts, and `by_category` precision/recall | -| `common_row_count_cells` | Over shared rows × shared samples: exact-match fraction, mean absolute error, Pearson r, and count totals with their ratio | +| `common_row_count_cells` | Exact-match fraction, mean absolute error, Pearson r, and count totals with their ratio over shared rows × shared samples | | `nonzero_union_count_cells` | The same agreement statistics over cells nonzero in either file | ## Interpreting the Results diff --git a/docs/src/commands/window-scan.md b/docs/src/commands/window-scan.md index f7ba73e..c6ca1af 100644 --- a/docs/src/commands/window-scan.md +++ b/docs/src/commands/window-scan.md @@ -10,35 +10,39 @@ madcats window-scan --probe-design --fastq-dir --lengths --o ## Description -Window length trades read retention against information. Longer windows carry more linked -variation, but fewer reads cover them fully and more reads carry errors. `window-scan` measures -three curves without external truth: - -| Curve | Measures | -|-------|----------| -| **Retention** | Fraction of located reads that fully cover the best window. Predicted for a dense grid of lengths from one coverage pass | -| **Cleanliness** | Assigned reads not merged away by denoising or dropped for failing the evidence rules | -| **Information** | Evidence-passing novel haplotype rows per 100 markers | - -Each candidate in `--lengths` runs the actual `normalize-reads` and `generate` code on a sample -subset. +Selecting a window length for `normalize-reads` involves a trade-off between sequence information +content and read coverage. Longer windows capture more linked variants, but fewer reads span them +completely and more reads accumulate sequencing errors. `window-scan` evaluates candidate window +lengths on a representative sample subset by running the full `normalize-reads` and `generate` +pipeline and measuring four metrics without requiring external truth: + +| Metric | Definition | +|--------|------------| +| Retention | Fraction of located reads fully covering the selected window (also predicted across a dense grid of lengths from a single coverage pass) | +| Assignment rate | Fraction of normalized reads assigned to a locus | +| Clean rate | Fraction of assigned reads passing evidence and denoising filters | +| Novel information rate | Number of evidence-passing novel microhaplotype rows discovered per 100 markers | ### How the length is chosen -*Survival* = retention × assignment × cleanliness. Candidates within `--info-band` (default 10%) of -the best survival are eligible. Among them, the most informative length wins, with ties going to the -shorter length. +Overall window performance is defined by a combined survival metric: +`survival = retention × assignment rate × clean rate`. All candidate lengths within `--info-band` +(default 10%) of the maximum observed survival score are eligible. Among eligible candidates, +`window-scan` selects the length that maximizes the novel information rate and resolves ties in +favor of the shorter window. -Information is not used on its own, because systematic errors (such as Ion homopolymer indels that -recur across samples) pass the reproducibility route and look like extra haplotypes. With this -rule, the scan picked the length that independent validation favored on every dataset tested: -41 bp on Ion oyster, 81 bp on GT-seq, and 61 bp on capture. +Relying on novel information alone can mislead selection because systematic errors (such as Ion +Torrent homopolymer indels recurring across samples) pass the reproducibility route and inflate +apparent allele counts. Using the survival band, `window-scan` selected the same length favored by +independent validation across every tested dataset: 41 bp on Ion Torrent oyster, 81 bp on GT-seq, +and 61 bp on Flex-Seq capture. ### Seed sensitivity -The recommendation can depend on which samples are scanned. `--scan-draws N` repeats the sweep on N -seeded draws, reports each draw's recommendation, and takes the most-voted length. If the -recommendation changes between draws, scan more samples or check the choice against external data. +Because recommendations can vary depending on which samples are selected, `--scan-draws N` repeats +the sweep across N independent seeded sample subsets, reports each draw's recommendation, and +selects the consensus length. If recommendations vary across draws, increase `--scan-samples` or +verify the length against external reference data. ## Required Arguments @@ -54,7 +58,7 @@ recommendation changes between draws, scan more samples or check the choice agai | Option | Default | Description | |--------|---------|-------------| | `--fastq-glob ` | `*` | FASTQ filename glob within `--fastq-dir` | -| `--scan-samples ` | 6 | Samples per candidate run: the first in sorted order, or a seeded draw | +| `--scan-samples ` | 6 | Samples per candidate run, taken as the first in sorted order or as a seeded draw | | `--scan-seed ` | none | Draw the subset at random with this seed | | `--scan-draws ` | 1 | Independent draws to sweep (seeds `--scan-seed`, +1, +2, ...) | | `--grid-step ` | 10 | Step for the dense predicted-retention grid | @@ -93,12 +97,12 @@ madcats window-scan \ | File | Contents | |------|----------| -| `OUT_DIR/window_scan.tsv` | One row per length: predicted and measured retention, assignment, cleanliness, information, survival, eligibility; then the dense retention grid | +| `OUT_DIR/window_scan.tsv` | One row per length with predicted and measured retention, assignment, cleanliness, information, survival and eligibility, followed by the dense retention grid | | `OUT_DIR/window_scan.qc.json` | Parameters, per-length results and `recommended_tag_length`. With several draws, also `recommendation_votes` and `recommendation_stability` | | `OUT_DIR/len_/` | Per-candidate run directories (under `OUT_DIR/draw_N/` when `--scan-draws` > 1) | -If tiles cannot be given distinct windows at some length, that length is reported as failed and the -scan continues. +If tiles cannot get distinct windows at some length, the scan reports that length as failed and +continues. ## Tips diff --git a/docs/src/development/architecture.md b/docs/src/development/architecture.md index 8fb2faf..4a9d7ea 100644 --- a/docs/src/development/architecture.md +++ b/docs/src/development/architecture.md @@ -1,40 +1,49 @@ # Architecture -MADCATS is a single module, `madcats.py`, that uses only the Python standard library. There is -nothing to compile and no dependency to pin, and the same file runs as a script (`python3 -madcats.py`), as the installed `madcats` command, or frozen into a standalone binary. +`madcats.py` holds the read-processing pipeline and uses only the Python standard library. +`madcats_paralogs.py` holds `filter-paralogs`, which needs the optional `mappy` aligner. +It imports that dependency when the command runs (`pip install 'madcats[genome]'`). +There is nothing to compile, and the same files run as a script +(`python3 madcats.py`), as the installed `madcats` command, or frozen into a standalone binary. ## Repository Layout | Path | Contents | |------|----------| -| `madcats.py` | The whole tool: library functions and the command line | +| `madcats.py` | Read processing, count-table generation and the main command line | +| `madcats_paralogs.py` | `filter-paralogs`, with genome alignment, marker placement, labels and the table filter | | `tests/` | Unit and end-to-end tests (`unittest`) | | `scripts/` | Diagnostic and conversion scripts (e.g. `madc_to_reference_tags.py`, `validate_inferred_design.py`) | | `docs/` | This documentation (mdBook), plus `DEVELOPMENT.md`, the long-form development record | | `examples/madcats-demo/` | Simulated example project and the script that generates it | -| `assets/` | Full-size logo (2028 × 2028 PNG); the docs use a 600 px copy in `docs/src/images/` | +| `assets/` | Full-size logo (2028 × 2028 PNG). The docs use a 600 px copy in `docs/src/images/` | | `packaging/` | PyInstaller entry point for the standalone binaries | | `pyproject.toml` | Package metadata for PyPI | -| `.github/workflows/` | Tests on every push; PyPI and binary releases on version tags | +| `.github/workflows/` | Tests on every push, and PyPI and binary releases on version tags | ## Reading Map of `madcats.py` -The module is laid out in the order a read travels. Each section opens with a banner comment: +The module follows the order a read travels. Each section opens with a banner comment: | Section | Contents | |---------|----------| | 0. Constants, errors and data types | `Locus`, `Sample`, `SampleResult`, MADC column definitions | | 1. Sequence and file utilities | IUPAC matching, mismatch counts, CSV/FASTQ helpers | -| 2. Alignment engine | Myers bit-vector prescreen, banded DP, `accepted_gapped_reading` / `row_reading` | +| 2. Alignment engine | Myers bit-vector prescreen, banded DP, `accepted_gapped_reading` / `row_decision` | | 3. Panel definition | Design-file reconstruction (`build_panel`), reference-tag tables, primer-free inference | | 4. Platform intake | Pair merging, window location and freezing, tiling and routing, window-scan | -| 5. Per-sample read assignment | `PrimerIndex`, `select_marker`, `process_sample` and its cache | +| 5. Per-sample read assignment | `PrimerIndex`, `select_markers`, `process_sample` and its cache | | 6. Evidence, denoising and partial-read salvage | `EvidenceRule`, `collect_evidence`, `finalize_counts`, `apply_partial_reads` | -| 7. Classification and annotation | `classify_sequence`, `variant_events`, `marker_type_label` | +| 7. Classification, annotation, and primer removal | `classify_sequence`, `variant_events`, `marker_type_label`, `amplicon_geometry`, `right_primer_cut`, `trim_locus_rows` | | 8. MADC input/output and QC | `read_madc`, `write_madc`, `validate_madc` | | 9. Commands and command line | One `run_*` per subcommand, `build_parser`, `main` | +`madcats_paralogs.py` follows the same order on a smaller scale: scoring and alignment +(`GenomeAligner`, `WindowIndex`), marker placement and labels (`place_marker`, `score_at_sites`, +`genome_label`), the two-pass table filter (`filter_paralogs`), then its command line. It imports +the MADC helpers it shares with `validate` from `madcats`, so `build_parser` imports it while +building the parser rather than at the top of `madcats.py`. + ## The `generate` Pipeline ``` @@ -52,22 +61,27 @@ FASTQs ──► 5. assign reads ──► (per-sample cache) 8. write MADC + QC JSON + variants sidecar ``` -Rows hold the exact sequences observed in reads, with no consensus correction, so the output can be -checked against the raw FASTQs. +Rows hold the exact sequences observed in reads, with no consensus correction, so you can check +the output against the raw FASTQs. -Decisions that several stages need are made in one place. The same `EvidenceRule` decides -discovery, which sequences denoising protects, and partial-read crediting, and the same -`row_reading` is used for classification and annotation, so those stages always agree. +Decisions that several stages need live in one place. The same `EvidenceRule` decides +discovery, which sequences denoising protects, and partial-read crediting. Classification, +annotation and primer removal read the same `row_decision`, so those stages always agree. ## Parallelism and Caching -- Per-sample read assignment, pair merging, normalization and inference run across a - `ProcessPoolExecutor` sized by `--jobs`. -- Since 0.12.1, `generate`'s finalisation also runs across the workers: per-sample denoising per - sample, and the pooled pass per locus. The result is identical to the sequential passes. -- The per-sample cache (`--cache-dir`) is keyed by the panel and every read-assignment parameter, - so downstream thresholds never invalidate it. `CACHE_FORMAT_VERSION` is bumped whenever the - serialized cache or raw-read processing changes. +- Per-sample read assignment, pair merging, normalization, and design inference run in parallel + across a `ProcessPoolExecutor` sized by `--jobs`. +- Since 0.12.1, `generate`'s finalization stage also runs in parallel across workers (per sample + for per-sample denoising and per locus for the pooled pass), producing results identical to + sequential execution. +- 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. ## Vocabulary @@ -78,4 +92,4 @@ discovery, which sequences denoising protects, and partial-read crediting, and t | *marker* / *locus* | The same panel entry (`Locus` is the record) | | *canonical* | The design's Ref and Alt tags | | *category* | Ref, Alt, RefMatch, AltMatch or Other, read at the target base | -| *anchor* | The prefix a read is assigned by: the left primer or a pseudo-primer | +| *anchor* | The prefix a read is assigned by, either the left primer or a pseudo-primer | diff --git a/docs/src/development/changelog.md b/docs/src/development/changelog.md index 3393bb2..bd02ae7 100644 --- a/docs/src/development/changelog.md +++ b/docs/src/development/changelog.md @@ -3,68 +3,113 @@ Notable changes by version. Measurements behind each change are in the [development record](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md) on GitHub. +## 0.14.0 + +- **New optional command `filter-paralogs` (experimental).** It drops or flags MADC rows that a + reference genome places at another locus, for panels where co-amplified paralogs inflate + heterozygosity. It requires the `mappy` aligner (`pip install 'madcats[genome]'`), and its + options and outputs may change. See [`filter-paralogs`](../commands/filter-paralogs.md). +- **`generate --remove-primers on` (default `off`).** MADCATS writes each row without its primers + and sums the counts of rows that become identical. A row keeps its right primer when the cut + would remove its target base, leave fewer than 10 bp, or merge it with a row of another allele + group, and the QC JSON lists those rows. See + [Removing Primers](../commands/generate.md#removing-primers). +- **Unresolved ends.** When a gapped alignment leaves fewer than 12 bp after its last gap, there + are too few trailing bases to distinguish an indel from substitutions. `generate` now marks + these rows `unresolved` (`unresolved=k` in `Variants`) and classifies them as `Other` when the + target falls in the unresolved region. When reads extend at least 12 bp past the tag, MADCATS + uses those downstream bases to resolve the alignment where possible. Default tables differ + slightly from 0.13.0. See [Classification](../reference/evidence-model.md#classification). +- **Ref and Alt alignment ties.** When gapped alignments to the Ref and Alt tags need the same + number of edits, `generate` now selects the alignment with fewer gaps, classifying Alt haplotypes + with an indel adjacent to the target as `AltMatch`. MADCATS also derives `Variants` from the same + alignment used for classification, and it writes an indel at base 1 or directly after a + substituted base without an anchor base (`1:.>GG`). +- **Tiled markers (`--tile-groups auto|declared|off`, default `auto`).** When a read matches + multiple tiled markers on the same amplicon, `generate` now credits it to each matching tile + instead of dropping it as an ambiguous tie. `--tile-groups off` restores the 0.13.0 read + assignment. See [Tiled Markers](../getting-started/input-formats.md#tiled-markers). +- **Leading anchor.** `--leading-anchor auto` now handles inline barcodes of different lengths. + `--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. +- **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 41% to 47% less time than with 0.13.0. + This release also revises the CLI help text across subcommands. + ## 0.13.0 -- Removed the `madc_pipeline` compatibility module. Import `madcats` instead; the bundled +- Removed the `madc_pipeline` compatibility module. Import `madcats` instead, as the bundled scripts already do. -- `--partial-read-mode` takes `on`/`off` like the other switches; the old value `assign` still +- `--partial-read-mode` takes `on`/`off` like the other switches, and the old value `assign` still works as `on`, with a warning. -- Clearer command-line help: every command has a description, every option has help text, and - the program is named `madcats` in usage lines. -- The development record (`docs/DEVELOPMENT.md`) is no longer published on the docs site; it - stays in the repository. +- Command-line help is clearer. Every command has a description, every option has help text, and + usage lines name the program `madcats`. +- The docs site no longer publishes the development record (`docs/DEVELOPMENT.md`), which stays in + the repository. - A small simulated example project, with its true haplotypes and genotypes, is included in `examples/madcats-demo` and attached to each release as `madcats-demo.tar.gz`. - The test suite checks that the command reference pages match each command's `--help`. ## 0.12.1 -- Packaged for PyPI: `pip install madcats` installs a `madcats` command. -- Standalone binaries for Linux and macOS are built for each release. -- New documentation site; the former README is now the development record, `docs/DEVELOPMENT.md`. +- Packaged for PyPI, so `pip install madcats` installs a `madcats` command. +- Each release comes with standalone binaries for Linux and macOS. +- New documentation site. The former README is now the development record, `docs/DEVELOPMENT.md`. - Licensed under GPL-3.0-or-later. -- `generate`'s finalisation (per-sample denoising and the pooled pass) runs across the `--jobs` +- `generate`'s finalization (per-sample denoising and the pooled pass) runs across the `--jobs` workers. The selection is identical to the sequential passes. On a 44-run rhAmpSeq family the pooled pass alone had taken 1,123 s in one process. ## 0.12.0 -- Raw DArT deliveries: `generate` and `infer-design` take `--leading-anchor SEQ|auto`. Reads are - cut where the common sequence ends; runs on an undeclared constant prefix stop and name it. -- Design route: a reconstructed tag must contain the bracketed variant, so primer occurrences +- For raw DArT deliveries, `generate` and `infer-design` take `--leading-anchor SEQ|auto`. They + cut reads where the common sequence ends, and runs on an undeclared constant prefix stop and name + it. +- On the design route, a reconstructed tag must contain the bracketed variant, so primer occurrences in duplicated flanks are no longer candidates. -- Denoiser scaling: at distance 1, parents are found by enumerating single-substitution - neighbours once centroids outnumber them, fixing quadratic time at highly paralogous loci. +- The denoiser scales better. At distance 1, it finds parents by enumerating single-substitution + neighbors once centroids outnumber them, fixing quadratic time at highly paralogous loci. Output is identical. ## 0.11.0 -- Partial reads (`--partial-read-mode assign`, now `on`; default): reads shorter than the tag are - added to an allele that already passed the evidence rules and whose start they match, only when - this cannot change an allele ratio. +- With partial reads (`--partial-read-mode assign`, now `on`, the default), reads shorter than the + tag count toward an allele that already passed the evidence rules and whose start they match, + only when this cannot change an allele ratio. `--min-partial-length` defaults to tag length − 9. The experimental `extend` mode was removed. -- One reading per row: classification and annotation share `row_reading`, so they cannot +- Classification and annotation share one reading per row (`row_reading`), so they cannot disagree. -- Freeze health: `normalize-reads --reuse-tags` scores frozen windows against the new run's reads. +- For freeze health, `normalize-reads --reuse-tags` scores frozen windows against the new run's + reads. - `window-scan --scan-draws` reports recommendation stability across seeded sample subsets. ## 0.10.0 -- Undesigned indel recovery: reads that fail substitution-only identity get one gapped +- For undesigned indel recovery, reads that fail substitution-only identity get one gapped alignment under the same edit limit (`--gapped-rescue`, `--max-indel-length`), with substitution and gap limits that keep paralogs out and a bit-vector prescreen for speed. - Target base read through the gapped alignment when that reading is cheaper and verified. -- Annotations (`--annotations on`, default): `Variants` and `MarkerType` columns and the +- Annotations (`--annotations on`, default) add `Variants` and `MarkerType` columns and the `OUTPUT.variants.csv` sidecar. -- The pooled denoising pass merges only into a same-allele parent; N-bearing tags are credited or - dropped, never emitted. +- The pooled denoising pass merges only into a same-allele parent, and credits or drops N-bearing + tags, never emitting them. - `window-scan` gains `--scan-seed` and `--generate-args`. - Cache format 0.5.0 (caches rebuild once). ## 0.9.0 -- Paired-end intake: the `merge-pairs` command, and pooled mates for dual-anchored designs. -- Multi-window tiling: the `LocusGroup` column, `--group-routing nearest|covered`, and the +- Paired-end intake, with the `merge-pairs` command and pooled mates for dual-anchored designs. +- Multi-window tiling, with the `LocusGroup` column, `--group-routing nearest|covered`, and the check that tiles excise distinct windows. - The `window-scan` command. - `--primer-mismatches` default changed from 0 to 1. @@ -90,12 +135,12 @@ Notable changes by version. Measurements behind each change are in the ## 0.7.0 -- Indel markers and degenerate (IUPAC) primers: one general window rule for SNPs, insertions, - deletions and homopolymer shifts; tags built as primer overlay plus genomic suffix. +- Indel markers and degenerate (IUPAC) primers, with one general window rule for SNPs, insertions, + deletions and homopolymer shifts, and tags built as primer overlay plus genomic suffix. ## 0.5.0 -- Evidence model redesign: reproducibility (primary), depth and optional quality routes, +- Evidence model redesign, with reproducibility (primary), depth and optional quality routes, combined by OR. Flags renamed so old commands stop with an error: - `--min-quality-support` → `--quality-min-clean-reads` (route now off by default) - `--novel-min-reads-per-sample` / `--novel-min-samples` → `--reproducible-min-reads` / @@ -107,6 +152,6 @@ Notable changes by version. Measurements behind each change are in the ## Earlier - `infer-design` for panels without a primer file. -- 0.3.x–0.4.x: quality-gated discovery and the exploratory audits that motivated 0.5.0. +- 0.3.x–0.4.x brought quality-gated discovery and the exploratory audits that motivated 0.5.0. - The tool was renamed from `madc_pipeline` to MADCATS, with `madc_pipeline.py` kept as a compatibility shim until 0.13.0. diff --git a/docs/src/development/contributing.md b/docs/src/development/contributing.md index 6ae3ea3..dd92b9e 100644 --- a/docs/src/development/contributing.md +++ b/docs/src/development/contributing.md @@ -1,7 +1,7 @@ # Contributing -Contributions are welcome: bug reports, documentation fixes, validation results on new platforms, -and code. +Contributions are welcome, such as bug reports, documentation fixes, validation results on new +platforms, and code. ## Development Setup @@ -15,7 +15,8 @@ source .venv/bin/activate pip install -e . ``` -No other dependencies are needed to develop or test. +Developing and testing need no other dependencies. The `filter-paralogs` tests that align to a +synthetic genome need `mappy` (`pip install -e '.[genome]'`), and the suite skips them without it. ## Running Tests @@ -29,21 +30,22 @@ window-scan, gapped alignment, denoising and partial reads. Tests run on every p request across Python 3.9–3.13 (`.github/workflows/tests.yml`). Two tests guard the documentation. `tests/test_docs.py` checks that each page in -`docs/src/commands/` lists exactly the options that command's `--help` shows, with matching -choices and defaults, so update the page whenever you add or change an option. +`docs/src/commands/` lists exactly the options of that command's `--help`, with matching choices +and defaults. Update the page whenever you add or change an option. `tests/test_example.py` runs the example in `examples/madcats-demo` and checks the output against its simulated truth. If a change alters the example's numbers, update [Try the Example](../getting-started/example.md) to match. To change the example data itself, edit and rerun `examples/madcats-demo/make_demo_data.py`. -Changes that touch counting should also be checked against real data. The standard is byte-for-byte: -a refactor regenerates existing tables identically from cache, and a behaviour change is measured -against a comparator before it becomes a default. Record those measurements in -[`docs/DEVELOPMENT.md`](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md). +Also validate changes that touch counting against real datasets. The standard is byte-for-byte +reproducibility: a refactor should regenerate existing tables identically from cache, and any +behavior change should be benchmarked against a comparator before becoming a default. Record those +benchmarks in [`docs/DEVELOPMENT.md`](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md). ## Code Style -- Standard library only. A new dependency needs a strong reason. +- Standard library only. A new dependency needs a strong reason. Only that command's module, + `madcats_paralogs.py`, imports the optional `mappy` extra for `filter-paralogs`. - Keep the section layout of `madcats.py` (see [Architecture](architecture.md)). - Every analysis threshold is a command-line option with a documented default. - Stop with a clear error on inconsistent input instead of writing a table that may be wrong. @@ -61,15 +63,15 @@ mdbook build docs # static site in docs/book/ ## Releasing -Releases are driven by a version tag. The version lives in one place, `__version__` in -`madcats.py`; `pyproject.toml` reads it from there. +A version tag drives each release. The version lives in one place, `__version__` in +`madcats.py`, and `pyproject.toml` reads it from there. 1. Bump `__version__` in `madcats.py` and add an entry to `docs/src/development/changelog.md`. 2. Commit, then tag and push: ```bash - git tag v0.13.0 - git push origin v0.13.0 + git tag v0.14.0 + git push origin v0.14.0 ``` 3. `.github/workflows/release.yml` then: @@ -95,10 +97,10 @@ pyinstaller --onefile --name madcats --paths . packaging/pyinstaller_entry.py ### One-time setup -- PyPI: on [pypi.org](https://pypi.org), add a *pending trusted publisher* for project +- For PyPI, add a *pending trusted publisher* on [pypi.org](https://pypi.org) for project `madcats` with owner `Breeding-Insight`, repository `MADCATS`, workflow `release.yml` and - environment `pypi`. No API token is stored in GitHub. -- Read the Docs: import the GitHub repository at + environment `pypi`. GitHub stores no API token. +- For Read the Docs, import the GitHub repository at [readthedocs.org](https://readthedocs.org/dashboard/import/) under the project slug `madcats`. Builds then run on every push. diff --git a/docs/src/getting-started/example.md b/docs/src/getting-started/example.md index 596b903..6383dc5 100644 --- a/docs/src/getting-started/example.md +++ b/docs/src/getting-started/example.md @@ -1,8 +1,8 @@ # Try the Example -MADCATS comes with a small simulated DArTag-style project that runs in seconds. The true -haplotypes and genotypes behind its reads are included, so you can check every row of the output -against what was simulated. +MADCATS comes with a small simulated DArTag-style project that runs in seconds. It includes +the true haplotypes and genotypes behind its reads, so you can check every row of the output +against the simulation. ## Get the Data @@ -24,17 +24,17 @@ The same files are in the repository under `examples/madcats-demo`. | `sample_names.csv` | Renames the samples from `S01` to `Line_01`, and so on | | `truth_haplotypes.csv` | Every simulated haplotype's 81-bp tag sequence | | `truth_genotypes.csv` | Each sample's simulated diploid genotype at each marker | -| `make_demo_data.py` | The script that made all of the above; rerunning it reproduces the files exactly | +| `make_demo_data.py` | The script that made all of the above. Rerunning it reproduces the files exactly | ## What Was Simulated -Twelve diploid samples, eight markers with 81-bp tags, and about 550 reads per sample. Beyond each -marker's designed Ref and Alt alleles: +The project has twelve diploid samples, eight markers with 81-bp tags, and about 550 reads per +sample. Beyond each marker's designed Ref and Alt alleles: -- **Chr02** and **Chr04** carry an extra microhaplotype: a second SNP on the Ref or Alt background. -- **Chr06** carries a haplotype with an undesigned 1-bp insertion. -- **Chr08** has no Alt allele in any sample. -- **Chr03** and **Chr07** have their primer on the reverse strand of the probe-design target. +- Chr02 and Chr04 carry an extra microhaplotype with a second SNP on the Ref or Alt background. +- Chr06 carries a haplotype with an undesigned 1-bp insertion. +- Chr08 has no Alt allele in any sample. +- Chr03 and Chr07 have their primer on the reverse strand of the probe-design target. - Every read has a 0.2% chance per base of a sequencing error, about 8% of reads are shorter than the tag, and each sample has a few off-target reads. @@ -60,8 +60,8 @@ madcats generate \ ## Check the Results -The table has 19 rows: a Ref and an Alt row for each of the 8 markers, plus the 3 microhaplotypes -MADCATS discovered. With MADCATS 0.13.0 the discovered rows are: +The table has 19 rows. There is a Ref and an Alt row for each of the 8 markers, plus the 3 +microhaplotypes MADCATS discovered. With MADCATS 0.13.0 and 0.14.0 the discovered rows are: | AlleleID | Variants | MarkerType | Reads (all samples) | |----------|----------|------------|--------------------:| @@ -71,21 +71,22 @@ MADCATS discovered. With MADCATS 0.13.0 the discovered rows are: Things to look for: -- **Every simulated haplotype is a row, and nothing else is.** Compare the `AlleleSequence` column - with `truth_haplotypes.csv`. The sequencing errors were merged back into their true haplotypes by - denoising, so none of them became rows. -- **The insertion was recovered.** Its reads failed the substitution-only identity check and were - placed by gapped alignment. `Variants` reports the insertion left-aligned (`29:G>GC`), and +- **The rows match the simulated haplotypes one to one.** Compare the `AlleleSequence` column + with `truth_haplotypes.csv`. Denoising merged the sequencing errors back into their true + haplotypes, so none of them became rows. +- **MADCATS recovered the insertion.** Its reads failed the substitution-only identity check, and + gapped alignment placed them. `Variants` reports the insertion left-aligned (`29:G>GC`), and `clip=1` notes that it pushed the last Ref base out of the 81-bp window. -- **Chr08 still has an Alt row.** Canonical Ref and Alt rows are always written. Its single read +- **Chr08 still has an Alt row.** MADCATS always writes canonical Ref and Alt rows. Its single read comes from a sequencing error that happened to hit the SNP base. - **Counts follow the genotypes.** In each `Line_` column, a heterozygous sample splits its reads between two haplotypes and a homozygous sample puts nearly all of them on one. Compare with `truth_genotypes.csv`. -- **Every read is accounted for.** The `read_accounting` section of the QC JSON shows 6,989 reads in - total, 129 assigned by gapped alignment, 466 partial reads added to counts, 851 merged away by - per-sample denoising, and 64 in error sequences that failed the evidence rules. Each sample's - entry in `sample_qc` also counts its off-target reads (`reads_no_primer`). +- **The QC JSON accounts for every read.** Its `read_accounting` section reports 6,989 total reads + and 129 assigned through gapped alignment. MADCATS credits 466 partial reads to full-length + alleles, absorbs 851 sequencing-error reads during per-sample denoising, and drops 64 reads from + error sequences that failed the evidence rules. Each sample entry under `sample_qc` also reports + off-target reads (`reads_no_primer`). ## Try Changing Something @@ -93,8 +94,8 @@ Each of these reruns `generate` with one setting changed: | Change | What happens | |--------|--------------| -| `--reproducible-min-samples 5 --depth-min-reads 0` | The 3 discovered rows disappear: each extra haplotype is carried by only 4 samples, and the depth route is off | -| `--gapped-rescue off` | The Chr06 insertion row disappears; its reads are no longer assigned | +| `--reproducible-min-samples 5 --depth-min-reads 0` | The 3 discovered rows disappear, because only 4 samples carry each extra haplotype and the depth route is off | +| `--gapped-rescue off` | The Chr06 insertion row disappears, because MADCATS no longer assigns its reads | | `--partial-read-mode off` | Same 19 rows, but reads in rows fall from 6,661 to 6,195 | To compare two runs, use `validate`: @@ -105,6 +106,6 @@ madcats validate --generated results/other_MADC.csv --expected results/demo_MADC ## Next Steps -- [Choosing a Workflow](workflows.md): which commands your own data needs -- [Evidence Model](../reference/evidence-model.md): how reads are assigned, discovered and denoised -- [Output Formats](../reference/output-formats.md): every column of the MADC table +- [Choosing a Workflow](workflows.md) to find which commands your own data needs +- [Evidence Model](../reference/evidence-model.md) on how MADCATS assigns, discovers and denoises reads +- [Output Formats](../reference/output-formats.md) for every column of the MADC table diff --git a/docs/src/getting-started/input-formats.md b/docs/src/getting-started/input-formats.md index a3ed33f..918d2dc 100644 --- a/docs/src/getting-started/input-formats.md +++ b/docs/src/getting-started/input-formats.md @@ -1,23 +1,23 @@ # Input Formats -MADCATS reads plain CSV/TSV design tables and FASTQ files. Column names are matched by header, so -extra columns are ignored. +MADCATS reads CSV/TSV design tables and FASTQ files. It finds columns by their header names, so it +ignores extra columns. ## FASTQs One FASTQ per sample, optionally gzipped, in a single folder (`--fastq-dir`). Restrict which files -are read with `--fastq-glob` (default `*`). +MADCATS reads with `--fastq-glob` (default `*`). -- `generate` expects **primer-started single-end reads**: every read begins at the assignment - anchor. Raw DArT deliveries with a barcode and common sequence in front are handled with - `--leading-anchor`. +- `generate` expects primer-started single-end reads, so every read must begin at the + assignment anchor. `--leading-anchor` handles raw DArT deliveries with a barcode and common + sequence in front. - `normalize-reads` accepts any read that contains a panel window, in either orientation. - `merge-pairs` expects mate files named by a shared stem plus `--r1-suffix` / `--r2-suffix` (defaults `_R1.fastq.gz` / `_R2.fastq.gz`), with mates in the same order. -Sample columns are named by the unique FASTQ filename stem unless a `--sample-lookup` table renames -them. Target manifests (`targets_*.csv`) in the FASTQ folder are picked up automatically for sample -metadata; they are optional. +MADCATS names sample columns by the unique FASTQ filename stem unless a `--sample-lookup` table +renames them. It picks up target manifests (`targets_*.csv`) in the FASTQ folder automatically for +sample metadata. They are optional. ## Primer CSV (DArT) @@ -26,13 +26,13 @@ Used by `design` and by `generate --primers`. | Column | Description | |--------|-------------| | `MarkerName` | Marker identifier, matching the probe design | -| `LeftPrimerSequence` | The primer every read starts with; may contain IUPAC codes for degenerate oligos | +| `LeftPrimerSequence` | The primer every read starts with, which may contain IUPAC codes for degenerate oligos | | `RightPrimerSequence` | Reverse primer | -| `VariantRef`, `VariantAlt` | Alleles. Indels use dash notation: `-` on the empty side | +| `VariantRef`, `VariantAlt` | Alleles. Indels use dash notation, with `-` on the empty side | | `VariantPositionInTagSequence` | Position of the variant (or the start of the indel span) in the tag | -Tags are reconstructed as the primer sequence verbatim plus the genomic continuation, matching the -vendor's representation of degenerate primers. +MADCATS reconstructs each tag as the primer sequence verbatim plus the genomic continuation, +matching the vendor's representation of degenerate primers. ## Probe Design (TSV/CSV) @@ -42,11 +42,12 @@ Used by `design`, `infer-design`, `normalize-reads` and `window-scan`. |--------|-------------| | `MarkerName` | Marker identifier | | `TargetSequence` | Target region with exactly one bracketed variant | -| `LocusGroup` | *Optional.* Declares markers as tiles of one physical locus | +| `LocusGroup` | *Optional.* Declares markers as tiles of one physical locus. See [Tiled Markers](#tiled-markers) | -The bracketed variant is a SNP such as `[C/T]` or an anchored-base indel such as `[A/ACTTG]` or -`[TTTTTTG/T]`. The first allele is the reference. Any DArT marker table with `MarkerName` and a -bracket-notation `TargetSequence` serves, extra markers and columns included. +The bracketed variant can be a SNP such as `[C/T]` or an anchored-base indel such as `[A/ACTTG]` or +`[TTTTTTG/T]`, with the reference allele listed first. Any DArT marker table containing `MarkerName` +and bracket-notation `TargetSequence` columns is supported, and extra markers or columns are +ignored. ``` MarkerName TargetSequence @@ -59,33 +60,79 @@ Panel construction rejects: - SNP designs whose constructed Alt tag is not among the bracket expansions (a primer-table / probe-design disagreement) -Members of a `LocusGroup` must present the same target region (identical Ref expansions differing -only in which variant is bracketed). Violations are load-time errors. +For `normalize-reads` and `window-scan`, members of a `LocusGroup` must present the same target +region (identical Ref expansions differing only in which variant is bracketed), or the panel does +not load. `design` and `generate --primers --probe-design` copy `LocusGroup` onto the panel +without that requirement. ## Reference Tags (CSV) -The platform-neutral panel definition consumed by `generate --reference-tags`. Written by `design`, -`infer-design` and `normalize-reads`, or curated by hand from any source. +This is the platform-neutral panel definition that `generate --reference-tags` consumes. `design`, +`infer-design` and `normalize-reads` write it, or you can curate it by hand from any source. | Column | Required | Description | |--------|----------|-------------| | `MarkerName` | yes | Marker identifier | -| `LeftPrimerSequence` | yes | Assignment anchor: the prefix reads are assigned by | +| `LeftPrimerSequence` | yes | Assignment anchor, the prefix MADCATS assigns reads by | | `RefSequence` | yes | Full-length Ref tag | | `AltSequence` | yes | Full-length Alt tag | | `VariantPositionInTagSequence` | when Ref and Alt differ at more than one base | Validated to point at a real Ref/Alt difference | | `VariantRef`, `VariantAlt` | no | Validated for IUPAC compatibility with the tag bases | | `RightPrimerSequence` | no | | -| `LocusGroup` | no | Tile grouping; written only when some locus uses it | +| `LocusGroup` | no | Tile grouping, written only when some locus uses it. See [Tiled Markers](#tiled-markers) | -Identical Ref/Alt sequences are rejected. Curated tags may contain IUPAC codes; see the -[evidence model](../reference/evidence-model.md#iupac-codes-and-n-bases) for what that means for -counts. +MADCATS rejects identical Ref/Alt sequences. Curated tags may contain IUPAC codes, and the +[evidence model](../reference/evidence-model.md#iupac-codes-and-n-bases) explains what that means +for counts. + +## Tiled Markers + +DArTag panels often tile multiple target SNPs within the same amplicon. These tiled markers share a +left primer, or one primer extends the other by one or two bases, so reads from the amplicon start +with both primers. Each tile's tag encodes its neighboring markers' SNPs as IUPAC ambiguity codes: + +``` +MarkerName,LeftPrimerSequence,RefSequence,...,VariantPositionInTagSequence,LocusGroup +Chr1_121673941,GGAAGACATGCTGAGGGYAC,GGAAGACATGCTGAGGGYACGTGTCATCRATTTCGG...,23,amp_Chr1_121673 +Chr1_121673947,GGAAGACATGCTGAGGGYAC,GGAAGACATGCTGAGGGYACGTKTCATCGATTTCGG...,29,amp_Chr1_121673 +``` + +Because reads from this amplicon match both tiles equally well, standard tie-breaking would discard +them as ambiguous and leave both markers with zero reads. With tile handling enabled, `generate` +instead credits each read to every tile in the family that it matches, matching DArT's pipeline (see +the [evidence model](../reference/evidence-model.md#tiled-markers)). + +Two markers qualify as tiles of the same amplicon when they cover the same tag window: + +- Their tags have the same length. +- One marker's left primer matches the start of the other marker's tag. +- Their Ref tags agree (allowing IUPAC codes) at every position except their respective target + variants. + +Markers linked by this rule form a tile family. `generate --tile-groups` controls which tile links +are active: + +| `--tile-groups` | Linked markers | +|-----------------|----------------| +| `auto` (default) | Markers sharing a `LocusGroup`, plus undeclared markers that pass the same-window test. Markers declared in different groups are never linked, directly or through an undeclared marker | +| `declared` | Only markers sharing a `LocusGroup` that also pass the same-window test | +| `off` | None (`generate` drops all ties as ambiguous) | + +You can declare `LocusGroup` in the reference-tag CSV or in the probe-design file when running +`design` or `generate --primers --probe-design` (`design` copies the column into the generated +reference tags). Tile detection uses only the primers and tag sequences, because reference-tag CSVs +do not carry genomic coordinates and any two markers covering the same tag window tie during read +assignment regardless of annotation. `generate` reports every active tile family on stderr and in +the QC JSON (`tile_families`). Under `declared` or `off`, it warns about markers that pass the +same-window test but remain unlinked. + +In `normalize-reads`, tiles within a `LocusGroup` are excised as distinct sequence windows rather +than sharing one tag window, so `generate` assigns each normalized read to a single marker as usual. ## Sample Lookup (CSV/TSV) -`generate --sample-lookup` takes a two-column table: FASTQ-derived sample id, then the desired -sample name. A header line is detected and skipped. +`generate --sample-lookup` accepts a two-column table mapping each FASTQ-derived sample ID to its +desired output sample name. An optional header line is detected and skipped automatically. ``` fastq_id,sample_name @@ -93,11 +140,10 @@ fastq_id,sample_name 4404076,Covington_rep1 ``` -The table is checked strictly, because a missing or wrong entry would put the wrong name on a count -column: every run sample must be mapped, ids that match no sample are errors, and duplicate names -are errors. +MADCATS validates this table strictly to prevent mislabeled sample columns. Every sample in the run +must have an entry, and any unmatched ID or duplicate output name stops the run with an error. ## Expected MADC -`validate --expected` reads any MADC, with or without the vendor's starred preamble rows: the header -is found by its `AlleleID` cell. +`validate --expected` reads any MADC, with or without the vendor's starred preamble rows, because it +finds the header by its `AlleleID` cell. diff --git a/docs/src/getting-started/installation.md b/docs/src/getting-started/installation.md index ba0b267..7a9e8ab 100644 --- a/docs/src/getting-started/installation.md +++ b/docs/src/getting-started/installation.md @@ -1,7 +1,9 @@ # Installation -MADCATS is a pure-Python tool with no third-party dependencies. Install it from PyPI (recommended), -download a standalone binary, or run it straight from a clone of the repository. +MADCATS is a pure-Python tool with no required third-party dependencies. You can install it from +PyPI (recommended), download a standalone binary, or run it directly from a repository clone. Only +the optional, experimental genome paralog filter (`filter-paralogs`) requires an extra dependency +([below](#optional-genome-aligner)). ## From PyPI (Recommended) @@ -27,6 +29,29 @@ pipx install madcats Upgrade later with `pip install --upgrade madcats` (or `pipx upgrade madcats`). +### Optional: Genome Aligner + +[`madcats filter-paralogs`](../commands/filter-paralogs.md) (experimental) aligns haplotypes to a +reference genome using `mappy`, minimap2's Python binding. Install it with the `genome` extra: + +```bash +pip install 'madcats[genome]' +``` + +If no pre-built wheel is available for your platform, `mappy` compiles minimap2 from source, which +requires a C compiler and zlib headers. All other commands run without `mappy`, and only +`filter-paralogs` imports it. The standalone binaries do not include `mappy`. + +On macOS, both the system Python and the python.org installers ship as universal binaries targeting +Apple Silicon and Intel simultaneously, which `mappy` cannot compile for in one pass. If +installation fails during compilation, build `mappy` specifically for your machine's architecture: + +```bash +ARCHFLAGS="-arch $(uname -m)" pip install 'madcats[genome]' +``` + +Single-architecture Python distributions, such as conda, do not require this workaround. + ## Pre-built Binaries Standalone executables bundle their own Python interpreter, so they run on machines without Python. @@ -74,19 +99,19 @@ tar -xzf madcats-macos-x86_64.tar.gz ./madcats --help ``` -> **Note for macOS users**: the binaries are not notarized. If macOS reports that the developer +> **For macOS users.** The binaries are not notarized. If macOS reports that the developer > cannot be verified, remove the quarantine flag: > > ```bash > xattr -d com.apple.quarantine madcats > ``` -The binary takes a couple of seconds to start (it unpacks its bundled interpreter on each run); -processing speed is the same as the pip-installed command. +The binary takes a couple of seconds to start (it unpacks its bundled interpreter on each run), +but processing speed is the same as the pip-installed command. ### Windows -No Windows binary is published yet. Install with `pip install madcats` under Python 3.9+. +There is no Windows binary yet. Install with `pip install madcats` under Python 3.9+. ## From Source @@ -111,7 +136,7 @@ madcats --version ``` ``` -madcats 0.13.0 +madcats 0.14.0 ``` To run the test suite from a source checkout: @@ -122,6 +147,6 @@ python3 -m unittest discover -s tests -v ## Next Steps -- [Quick Start](quickstart.md): generate your first MADC -- [Try the Example](example.md): run a small simulated project in seconds -- [Choosing a Workflow](workflows.md): which commands your data needs +- [Quick Start](quickstart.md) to generate your first MADC +- [Try the Example](example.md) to run a small simulated project in seconds +- [Choosing a Workflow](workflows.md) to find which commands your data needs diff --git a/docs/src/getting-started/quickstart.md b/docs/src/getting-started/quickstart.md index 893a9f7..f1c8684 100644 --- a/docs/src/getting-started/quickstart.md +++ b/docs/src/getting-started/quickstart.md @@ -1,17 +1,19 @@ # Quick Start -This page takes a DArTag project from FASTQs to a MADC table. Other platforms add a step or two -before `generate` (see [Choosing a Workflow](workflows.md)), and all of them finish with it. +This guide walks through a DArTag project from raw FASTQ files to a MADC table. Other platforms add +one or two preprocessing steps before `generate` (see [Choosing a Workflow](workflows.md)), and +every workflow finishes with `generate`. ## What You Need -- One FASTQ file per sample (`.fastq` or `.fastq.gz`), all in one folder -- The assay design. For DArTag, that is the vendor's primer-sequence CSV and probe-design file. +- One FASTQ file per sample (`.fastq` or `.fastq.gz`) in a single folder +- The assay design files (for DArTag, the vendor's primer-sequence CSV and probe-design file) ## Step 1: Build the Panel -`madcats design` reconstructs each marker's canonical Ref and Alt tags from the design files. No -reads are involved; the result is a platform-neutral reference-tag CSV you can inspect and reuse. +`madcats design` reconstructs each marker's canonical Ref and Alt tags from the design files without +reading any FASTQ data. The result is a platform-neutral reference-tag CSV that you can inspect and +reuse across projects. ```bash madcats design \ @@ -37,25 +39,26 @@ madcats generate \ --output results/project_MADC.csv ``` -`generate` can also read the design files directly (`--primers` + `--probe-design` in place of -`--reference-tags`). The defaults are the recommended configuration; no evidence flags are needed. +`generate` can also read the design files directly (`--primers` and `--probe-design` instead of +`--reference-tags`). The default settings are recommended for standard projects, so you do not need +to supply extra evidence flags. -This writes: +This writes three files: | File | Contents | |------|----------| -| `results/project_MADC.csv` | The MADC table: one row per allele, one read-count column per sample | -| `results/project_MADC.csv.qc.json` | Parameters, provenance and per-sample read accounting | -| `results/project_MADC.csv.variants.csv` | One line per variant event per row | +| `results/project_MADC.csv` | The MADC table, with one row per allele and one read-count column per sample | +| `results/project_MADC.csv.qc.json` | Run parameters, provenance, and per-sample read accounting | +| `results/project_MADC.csv.variants.csv` | Sidecar table with one line per variant event per row | -`--cache-dir` stores per-sample assignment results, so re-running with different evidence or -denoising settings skips the expensive read pass. As a reference point, an 80-sample, 155M-read -DArTag project processes from scratch in about 4.5 minutes with 8 workers and regenerates from a -warm cache in about a minute. +`--cache-dir` stores per-sample assignment results, so rerunning with different evidence or +denoising thresholds skips the read-assignment pass. As a benchmark, an 80-sample, 155M-read DArTag +project finishes from scratch in about 4.5 minutes on 8 workers and regenerates from a warm cache in +about one minute. -> **Raw DArT deliveries.** Older DArT orders keep an inline barcode and the common sequence -> `GATGGATCCAGTGC` in front of every amplicon. MADCATS detects this and stops with a message -> naming the prefix; re-run with `--leading-anchor auto` (or pass the sequence explicitly). +> **Raw DArT deliveries.** Older DArT deliveries retain an inline barcode and the common sequence +> `GATGGATCCAGTGC` in front of every amplicon. MADCATS detects this automatically and stops with a +> message naming the prefix. Rerun with `--leading-anchor auto` (or pass the sequence directly). ## Step 3 (Optional): Compare Against a Vendor MADC @@ -70,10 +73,10 @@ madcats validate \ ## Process the Whole Cohort at Once -Run **one** `generate` over every sample whenever novel-allele discovery matters. The +Run one `generate` over every sample whenever novel-allele discovery matters. The reproducibility evidence route counts supporting samples within the run, so splitting a cohort -into batches weakens discovery in proportion to the split. Expensive upstream stages such as -`normalize-reads` can be batched freely; feed all of their outputs to a single `generate`. +into batches weakens discovery in proportion to the split. You can batch expensive upstream stages +such as `normalize-reads` freely, but feed all of their outputs to a single `generate`. ## Next: HapApp @@ -89,7 +92,7 @@ See [Output Formats](../reference/output-formats.md) for details. ## Next Steps -- [Try the Example](example.md): run these steps on a small simulated project and check the output -- [Choosing a Workflow](workflows.md): routes for other platforms and inputs -- [madcats generate](../commands/generate.md): every option, grouped by pipeline stage -- [Evidence Model](../reference/evidence-model.md): when a new sequence is reported as a row +- [Try the Example](example.md) to run these steps on a small simulated project and check the output +- [Choosing a Workflow](workflows.md) with routes for other platforms and inputs +- [madcats generate](../commands/generate.md) for every option, grouped by pipeline stage +- [Evidence Model](../reference/evidence-model.md) on when MADCATS reports a new sequence as a row diff --git a/docs/src/getting-started/workflows.md b/docs/src/getting-started/workflows.md index 4fa1949..7fd65b1 100644 --- a/docs/src/getting-started/workflows.md +++ b/docs/src/getting-started/workflows.md @@ -1,32 +1,32 @@ # Choosing a Workflow -Every `generate` run consumes one **panel definition**: a reference-tag CSV holding each marker's -fixed-length Ref and Alt tag sequences plus an assignment anchor. Which commands you run before -`generate` depends on two questions: *how will you get the panel?* and *are your reads -primer-started?* +Every `generate` run requires a panel definition: a reference-tag CSV listing each marker's +fixed-length Ref and Alt tag sequences along with its assignment anchor. Which preprocessing +commands you run before `generate` depends on two questions: how you build the panel definition, and +whether your reads begin directly at a fixed primer boundary. ## Step 1: Define the Panel | You have | Use | Notes | |----------|-----|-------| -| Vendor primer CSV + probe-design file | [`madcats design`](../commands/design.md) | Uses no reads and gives the same result every time. The other routes were validated against it. | -| A vendor-delivered MADC from the same panel | `scripts/madc_to_reference_tags.py` | Reproduces the vendor's tags exactly, including its IUPAC curation. | -| Probe-design file only | [`madcats infer-design`](../commands/infer-design.md) | Selects each tag window from read evidence. Freeze the result and reuse it. | -| A curated Ref/Alt tag table from any source | Use it directly | `generate` accepts any reference-tag CSV in the documented format, whatever made it. See [Input Formats](input-formats.md). | -| Reads that are not primer-started | [`madcats normalize-reads`](../commands/normalize-reads.md) | Produces the panel *and* pipeline-ready FASTQs together. | +| Vendor primer CSV + probe-design file | [`madcats design`](../commands/design.md) | Deterministic and requires no reads. Serves as the reference when validating other panel routes. | +| A vendor-delivered MADC from the same panel | `scripts/madc_to_reference_tags.py` | Reproduces the vendor's canonical tags verbatim, including IUPAC curation. | +| Probe-design file only | [`madcats infer-design`](../commands/infer-design.md) | Infers each tag window from read evidence. Freeze the resulting CSV and reuse it across projects. | +| A curated Ref/Alt tag table from any source | Use it directly | `generate` accepts any reference-tag CSV following the documented schema (see [Input Formats](input-formats.md)). | +| Reads that do not start at a primer | [`madcats normalize-reads`](../commands/normalize-reads.md) | Generates both the panel definition and normalized, pipeline-ready FASTQ files. | ## Step 2: Match the Read Geometry | Read geometry | Platforms | Route | |---------------|-----------|-------| -| Single-end, every read starts with the primer | DArTag, GT-seq R1 | Straight to `generate` | -| Raw DArT delivery (barcode + common sequence before the amplicon) | Older DArTag orders | `generate --leading-anchor auto` | -| Bidirectional, variable start positions | AgriSeq (Ion Torrent) | `normalize-reads`, then `generate` | -| Paired-end, mates overlap | GT-seq PE, rhAmpSeq | `merge-pairs`, then `normalize-reads` or `generate` | -| Paired-end, mates cannot overlap | Flex-Seq (dual-anchored capture) | Pool both mates per sample, then `normalize-reads` | +| Single-end, every read starts with the primer | DArTag, GT-seq R1 | Run `generate` directly | +| Raw DArT delivery (barcode + common sequence before the amplicon) | Older DArTag orders | Run `generate --leading-anchor auto` | +| Bidirectional reads with variable start positions | AgriSeq (Ion Torrent) | Run `normalize-reads`, then `generate` | +| Paired-end reads with overlapping mates | GT-seq PE, rhAmpSeq | Run `merge-pairs`, then `normalize-reads` or `generate` | +| Paired-end reads with non-overlapping mates | Flex-Seq (dual-anchored capture) | Concatenate both mates per sample (or use `merge-pairs --unmerged pool` for mixed libraries), then run `normalize-reads` | -MADCATS does not detect paired-end data automatically: check how your reads are laid out and choose -the route yourself. Adapter trimming is not required on any route. +MADCATS does not auto-detect paired-end layouts, so verify your assay's read geometry and choose the +matching route. None of these routes requires adapter trimming. ## Common Pipelines @@ -71,10 +71,22 @@ madcats generate --fastq-dir norm/ --fastq-glob "*.fastq" \ See [Paired-End Reads and Tiling](../tutorials/paired-end.md). +## Optional: Filter Paralogs With a Reference Genome (Experimental) + +If co-amplified paralogous copies inflate heterozygosity in your panel, you can filter the finished +MADC (from `generate`, a vendor delivery, or HapApp) against a reference genome using the +experimental `filter-paralogs` command: + +```bash +madcats filter-paralogs --madc MADC.csv --genome genome.fa --genome-index genome.sr.mmi --output MADC_filtered.csv +``` + +See [Filtering Paralogs with a Reference Genome](../tutorials/paralog-filter.md). + ## Freeze Windows Across Runs -A primer-defined tag is fixed by the chemistry, but `normalize-reads` places each window based on -the reads, so the same panel re-run on new data can place windows differently and make identical -biology look like new haplotypes. After the first run of a panel, pass its window CSV to every later -run with `--reuse-tags`. On two honeybee chips this raised cross-chip haplotype sharing from 42% to -88%. +Primer-anchored chemistries fix each tag boundary physically, whereas `normalize-reads` learns +window placement from observed read coverage. Re-learning windows on a new batch can shift window +coordinates slightly and make identical alleles look like novel haplotypes. After your baseline run +for a panel, pass its `window_reference_tags.csv` to every subsequent run with `--reuse-tags`. On +two honeybee chips, freezing windows increased cross-chip haplotype sharing from 42% to 88%. diff --git a/docs/src/reference/evidence-model.md b/docs/src/reference/evidence-model.md index c5c8eed..1a69232 100644 --- a/docs/src/reference/evidence-model.md +++ b/docs/src/reference/evidence-model.md @@ -1,124 +1,242 @@ # Evidence Model -This page explains how `madcats generate` decides which reads count, which sequences become rows, -and how sequencing errors are removed. The design rationale and the measurements behind each default -are in the [development record](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md) on GitHub. +This page describes the internal analytical steps `madcats generate` uses to assign reads to target +loci, identify novel microhaplotypes, remove sequencing errors, and classify alleles. The design +rationale and benchmark measurements behind each default are recorded in the +[development record](https://github.com/Breeding-Insight/MADCATS/blob/main/docs/DEVELOPMENT.md) on GitHub. ## Read Assignment -For each marker, the panel holds a fixed-length Ref tag and Alt tag that both start with an -assignment anchor (the left primer, or a pseudo-primer prefix). - -1. A read is assigned to a marker by its prefix (the anchor). One mismatch is allowed by default - (`--primer-mismatches 1`). Anchors that are prefixes of longer anchors are supported, and every - anchor within the mismatch limit is considered. A read that matches several markers goes to the - one whose full tag it matches best; if that is a tie, the read is dropped as ambiguous. -2. The read's first tag-length bases are kept if they have at least `--min-identity` (80%) identity - to the marker's Ref or Alt tag, counting substitutions only. -3. If the read fails for every candidate marker, it gets one gapped alignment under the same 20% - edit limit, with gaps of up to `--max-indel-length` (10) bases. The alignment is kept only if it - looks like an indel allele: at most 6 substitutions and 6 gap events. Reads from co-amplified - paralogs need many substitutions to fit, so they are rejected. A fast bit-vector edit-distance - bound skips tags that cannot match before any alignment runs. -4. A read shorter than the tag is added to the one full-length allele whose start it matches - exactly, but only if that allele has already passed the evidence rules and the read is longer - than every prefix shared between two alleles of its locus. A partial read can therefore add to an - allele's count, but it cannot create an allele or change an allele ratio. Reads shorter than - `--min-partial-length` (tag length − 9) are never counted. +For each marker, the panel definition specifies a fixed-length canonical Ref tag and Alt tag, both +beginning with an assignment anchor (either the physical left primer or a synthetic assignment +prefix). + +1. **Primer trie lookup.** `generate` walks the start of each read along a trie containing every + panel anchor, allowing up to one mismatch by default (`--primer-mismatches 1`) to account for + sequencing errors or SNPs inside the primer region. Because a shorter anchor can be a prefix of a + longer anchor, MADCATS evaluates every candidate marker matched within the mismatch limit. When a + read matches multiple markers, it is assigned to the marker whose canonical tag it matches most + closely. Ties across unrelated markers are dropped as ambiguous, except within a family of + [tiled markers](#tiled-markers). +2. **Substitution-only identity check.** MADCATS extracts the first tag-length bases and compares + them against the marker's canonical Ref and Alt tags. The read is accepted if it meets + `--min-identity` (default 80%) to either canonical tag using substitutions alone (for example, up + to 10 mismatches on a 54 bp tag). +3. **Indel rescue.** If a read matches at least one primer but fails the substitution-only identity + check across all candidate markers, MADCATS attempts a single banded gapped alignment under the + same 20% edit limit with gaps up to `--max-indel-length` (default 10 bp). To reject divergent + paralogous reads that require many substitutions, an alignment is accepted only if it contains at + most 6 substitutions and 6 gap events. A Myers bit-vector prescreen skips tags that cannot meet + the edit bound before running dynamic programming. +4. **Partial-read salvage.** Reads shorter than `--tag-length` (but at least `--min-partial-length`, + default tag length − 9) are credited to a full-length allele only when they match its start + exactly, that allele already passes the evidence rules, and the read is longer than any prefix + shared by two alleles at that locus. Partial reads can therefore add depth to an established + allele without creating new alleles or distorting allele ratios. + +### Tiled markers + +Tiled markers are markers that read the same tag window of a single amplicon. DArTag panels +frequently target multiple SNPs within one amplicon under a shared (or nested) left primer, encoding +neighboring target SNPs as IUPAC ambiguity codes in each tile's tag. Because reads from that +amplicon match every tile equally well, standard tie-breaking would discard them as ambiguous and +leave all tiles with zero reads. `--tile-groups` (default `auto`) links tiled markers into families, +using declared `LocusGroup` labels and sequence-based detection (see +[Tiled Markers](../getting-started/input-formats.md#tiled-markers) for the same-window criteria). + +When the best match, or all tied best matches, belong to the same tile family, the read originated +from that family's amplicon. `generate` credits the read to every tile in the family that it matches +within the identity limit (either by substitutions alone or through a single gapped alignment), +recording the read's exact tag sequence for each tile. Each tile therefore receives the same counts +it would get in a standalone single-marker panel, matching DArT's pipeline. Partial reads follow the +same rule. Ties between markers from different tile families, or between a tile and an unlinked +marker, are still discarded as ambiguous. + +Because tiled markers share underlying reads, their read counts are not statistically independent. +Treat linked tiles as one locus, or retain one tile per family, in downstream analyses that assume +independent markers. ## Which Sequences Become Rows -Canonical Ref and Alt rows are always written, even with zero counts. +`generate` always emits the canonical Ref and Alt rows for every marker, even when their read counts +are zero. -Any other sequence becomes a row when it reaches `--min-global-count` reads project-wide **and** -passes at least one enabled evidence route: +Any novel sequence becomes an emitted row only if it reaches `--min-global-count` total reads across +the project and passes at least one enabled evidence route: | Route | Default | Rule | |-------|---------|------| -| **Reproducibility** (primary) | on | At least `--reproducible-min-reads` (10) reads in each of at least `--reproducible-min-samples` (2) samples | -| **Depth** | on | At least `--depth-min-reads` (30) reads within a single sample. Keeps private alleles discoverable in unreplicated designs | -| **Quality** | off | At least `--quality-min-clean-reads` reads whose every tag base reaches `--discovery-min-quality` (Q20) | +| Reproducibility (primary) | on | At least `--reproducible-min-reads` (10) reads in at least `--reproducible-min-samples` (2) samples | +| Depth | on | At least `--depth-min-reads` (30) reads within a single sample (retains private alleles in unreplicated designs) | +| Quality | off | At least `--quality-min-clean-reads` project-wide reads where every tag base meets `--discovery-min-quality` (Q20) | -Routes combine by OR. Identical tag sequences that recur independently across samples are strong -evidence, even when one base position is systematically low quality, which is why reproducibility -is primary and the whole-tag quality route is off by default. +Enabled routes combine by logical OR. Identical tag sequences that recur independently across +multiple samples provide strong biological evidence even if one base position has systematically low +base quality. Reproducibility is therefore the primary route, while the whole-tag quality route is +disabled by default. ### Supporting-frequency floor -`--min-supporting-freq` (default 0, off) additionally requires a sample's reads for the sequence to -reach that share of the sample's locus total before the sample can support the reproducibility or -depth route. +`--min-supporting-freq` (default 0, disabled) sets the minimum fraction of a sample's locus reads a +sequence must represent before that sample can support it in the reproducibility or depth route: -- At very high depth (above roughly 500x per sample per marker, e.g. AgriSeq), use `0.10`. At these - depths sequencing errors pass absolute thresholds, and per-marker depth varies tenfold within a - run, so a share-based floor works better than raising the absolute thresholds. -- For unreplicated designs that rely on the depth route, around `0.01` is a reasonable safeguard. -- Otherwise, leave it off. Co-amplified paralogs add reads to a locus, so real minor haplotypes can - fall below 1% of its reads. +- At very high sequencing depth (above roughly 500x per sample per marker, such as AgriSeq), use + `0.10`. At these depths, recurring sequencing errors pass absolute read thresholds, and per-marker + depth can vary tenfold within a run, making a proportional floor more effective than raising + absolute count thresholds. +- For unreplicated designs relying heavily on the depth route, a small floor around `0.01` helps + suppress low-level error artifacts. +- Otherwise, leave it disabled. Co-amplified paralogs inflate total read depth at a locus, which can + push genuine minor alleles below 1% of locus reads. ## Denoising -Canonical sequences and sequences that pass the evidence rules are protected: denoising never merges -them into anything else. - -1. Per-sample denoising (UNOISE-style abundance skew). Within each sample, a rare sequence that differs at - no more than `--denoise-distance` (1) bases from a more abundant parent is merged into the parent when the - parent is at least `2^(alpha·d + 1)` times more abundant (`--denoise-alpha` 2.0). The closest - parent is chosen first, then the most abundant. -2. Pooled same-allele merge (`--global-denoise-distance`, 1). A sequence that failed the evidence - rules is merged into the protected parent chosen from project-wide abundances, but only when both - carry the same target allele, so no merge can change a sample's Ref/Alt dosage. - -Reads in sequences that pass no route and have no parent are dropped, and the QC read accounting -reports them. Setting every route threshold to 0 writes every sequence with at least -`--min-global-count` reads (exhaustive discovery). - -The same evidence rule decides discovery, denoising protection and partial-read crediting, so the -three stay consistent. +Canonical Ref and Alt sequences, along with any novel sequences that pass the evidence rules, are +protected and are never absorbed into another sequence during denoising. + +1. **Per-sample denoising (UNOISE2 abundance skew).** Within each sample and locus, `generate` + absorbs low-abundance non-protected sequences into a parent differing by at most + `--denoise-distance` (default 1) substitutions whenever the parent has at least + `2^(alpha · d + 1)` times as many reads (`--denoise-alpha`, default 2.0, giving an 8x ratio at + `d = 1`). When multiple candidate parents qualify, MADCATS picks the closest Hamming distance + first and breaks ties by highest read count. +2. **Pooled same-allele merge (`--global-denoise-distance`, default 1).** After per-sample + denoising, `generate` pools read counts across all samples per locus and merges any remaining + evidence-failing sequence into the protected or canonical parent identified by project-wide + abundance skew, provided both sequences carry the **same target allele**. Restricting pooled + merges to the same target allele prevents the pooled merge from altering a sample's Ref/Alt + dosage. + +Reads belonging to non-protected sequences that fail every evidence route and do not merge into a +parent are dropped and tallied in the QC JSON read accounting. Disabling all evidence routes emits +every sequence meeting `--min-global-count` (exhaustive discovery). + +The same `EvidenceRule` governs discovery, denoising protection, and partial-read salvage so all +three stages remain consistent. ## Classification -Each row is classified against its marker's canonical tags: +`generate` classifies each emitted row by comparing its target allele against the marker's canonical +Ref and Alt tags: | Category | Meaning | |----------|---------| -| `Ref` | The canonical Ref tag | -| `Alt` | The canonical Alt tag | -| `RefMatch` | Carries the Ref target allele plus other differences | -| `AltMatch` | Carries the Alt target allele plus other differences | -| `Other` | Neither target allele: the target base is a third base, missing, or deleted | - -The target base is normally read at its fixed offset in the tag. When a gapped alignment explains -the row with fewer edits, stays within the substitution and gap limits, and is confirmed by at least -12 bases after its last gap, the target base is read from that alignment instead. A target inside a -deletion, or pushed past the end of the read, is `Other`. +| `Ref` | Exact match to the canonical Ref tag | +| `Alt` | Exact match to the canonical Alt tag | +| `RefMatch` | Carries the Ref target allele along with one or more secondary differences | +| `AltMatch` | Carries the Alt target allele along with one or more secondary differences | +| `Other` | Carries neither target allele (a third base, a deleted target, or an unread target) | + +With `--gapped-rescue on` (default), `generate` reads the target base at its fixed offset unless a +banded gapped alignment explains the sequence with strictly fewer edits, stays within the +substitution and gap limits, and leaves at least 12 aligned bases after its final gap. If the target +base falls inside a deletion or is shifted past the end of the tag by an upstream insertion, the row +is classified as `Other`. + +`generate` aligns each row against both the canonical Ref tag and the canonical Alt tag and selects +the alignment with fewer total edits. If both alignments tie on total edits, MADCATS chooses the one +with fewer separate gaps. This ensures that an Alt haplotype carrying a single indel beside the +target SNP is classified as `AltMatch` rather than as a `RefMatch` haplotype with two separate +indels flanking the target. If the alignments also tie on gap count, the Ref tag alignment is used. + +Gapped classification applies even to rows whose reads passed the initial substitution-only identity +check, because an upstream insertion shifts the target base right and a deletion shifts it left. +`Variants` annotations are derived from the same winning alignment (reported in 1-based Ref tag +coordinates with indels left-normalized), ensuring that a row's allele category and its `Variants` +column always agree on the target base. + +**Unresolved ends.** Sometimes a gapped alignment explains a row with fewer edits than substitutions +alone, yet leaves fewer than 12 bases after its final gap. In that trailing region, there are too +few downstream bases inside the tag to distinguish a true indel from a cluster of substitutions. +Rather than guessing, `generate` reads the sequence up to the first position where the two +explanations diverge and stops there: + +- If the target position lies at or after the divergence point, the row is classified as `Other`. +- If the target position lies before the divergence point, it is classified normally. +- The `Variants` column appends `unresolved=k`, and `MarkerType` is set to `unresolved` (see + [Output Formats](output-formats.md)). +- The QC JSON tallies these rows and their reads under `output_summary.unresolved_ends`. + +If an alignment contains an earlier gap whose following 12 bases match with at most 2 mismatches, +that earlier gap is accepted and only the trailing region starting at the later unverified gap is +marked unresolved. + +**Read continuation.** When sequencing reads extend past the tag length, those extra downstream +bases can resolve an ambiguous trailing gap. During the read pass, `generate` collects downstream +bases following the canonical Ref and Alt tags and any tag whose target falls in an unresolved end, +pooling them across samples. It then re-evaluates each affected row across the extended window +(appending each sequence's pooled downstream bases to the row, Ref tag, and Alt tag). The extended +alignment either confirms the gap and classifies the target through it, confirms the substitution +reading at the fixed offset, or leaves the row unresolved. Settled rows are reported normally with +`Variants` covering the tag length, while any target pushed past the tag by an insertion remains +`Other`. Read continuation only re-evaluates rows whose target lies in an unresolved end, so it +never alters the category of any other row. + +To keep per-sample processing fast, `generate` starts recording continuations for a tag once a +sample accumulates at least 3 reads of that tag. Across the cohort, a continuation sequence is used +only when supported by at least 3 reads and at least 60% of the tag's reads reaching the comparison +length (defined per tag as the longest length reached by at least 90% of its reads). The extended +window must add at least 12 bases beyond the tag and align those added bases with at most 2 +substitutions. Because reads must extend at least 12 bp past the tag, read continuation does not +trigger on fixed-length `normalize-reads` output. The QC JSON reports the comparison length and +settled row/read counts under `output_summary.read_continuation`. + +**Fixed offsets.** With `--gapped-rescue off`, both classification and variant annotation use fixed +tag offsets and never emit `unresolved` rows. Indel reads that still pass the 80% substitution-only +identity check can then receive incorrect categories, with the indel reported as multiple +substitutions. Even with `--gapped-rescue on`, `generate` falls back to fixed offsets when no gapped +alignment meets the edit and gap-length limits (for example, a deletion wider than +`--max-indel-length`). Agreement between a row's category and its `Variants` column confirms +internal consistency rather than independent proof of the underlying biological event. + +`--remove-primers on` operates after classification and preserves every row's assigned category, +changing only the printed sequences and coordinates. If removing the right primer would cause rows +from different allele groups to collapse into the same sequence, non-canonical colliding rows retain +their right primer and remain separate so reads never move between target alleles +(`primer_removal.rows_right_primer_kept_collision` in the QC JSON, see +[Removing Primers](../commands/generate.md#removing-primers)). ## IUPAC Codes and N Bases -Classification respects ambiguity codes in the design: if a design allele carries an ambiguity -code, an observed base compatible with it classifies as RefMatch/AltMatch. +Classification respects IUPAC ambiguity codes in the panel design: an observed base compatible with +a design ambiguity code matches it without incurring a mismatch and classifies as `RefMatch` or +`AltMatch`. -Row identity and counts use exact sequence equality, so an ambiguity-coded canonical tag reports -zero exact counts. MADCATS does not guess which concrete variants a curated IUPAC consensus was -meant to cover, because such codes can stand for real secondary SNPs, and collapsing them would -merge distinct microhaplotypes. +Row identity and read counts rely on exact sequence equality, so a canonical tag containing an IUPAC +code reports zero exact counts. MADCATS does not collapse concrete haplotypes into an IUPAC +consensus because ambiguity codes often represent genuine secondary SNPs that distinguish real +microhaplotypes. -A read containing N never becomes a row of its own. It is added to the one N-free sequence at its -locus that it is compatible with, or dropped (`reads_n_mapped` / `reads_n_dropped` in the QC). +Reads containing an ambiguous base `N` never form their own MADC row. `generate` credits each N-read +to the single N-free sequence at that locus compatible with it, or drops it if zero or multiple +sequences match (`reads_n_mapped` and `reads_n_dropped` in the QC JSON). ## Indels -Designed indel markers are fully supported. Vendors report indel alleles as fixed-length windows -whose suffix shifts at the indel, so both tags are ordinary same-length sequences. +`generate` handles designed indel markers identically to SNP markers. Following vendor convention, +designed indel alleles are represented as fixed-length tags whose trailing sequence shifts at the +indel, so both canonical tags share the same length. -Undesigned indels are recovered by the gapped alignment step above and written as fixed-length -rows in the same shifted-suffix convention. Indels longer than `--max-indel-length` are not -recovered, and neither are alignments that need many substitutions, which usually come from -paralogs. +The gapped rescue alignment recovers undesigned indels and emits them as fixed-length rows using the +same shifted-suffix convention. Indels wider than `--max-indel-length`, or alignments requiring more +than 6 substitutions or 6 gaps (typical of diverged paralogs), are not rescued. ## Read Accounting -The QC JSON accounts for every read: FASTQ records, reads assigned at full length, reads assigned -through a gapped alignment (`reads_assigned_gapped`), partial reads credited, ambiguous or unmapped, -reads moved by each denoising pass, reads dropped with low-evidence sequences, and per-sample -`reads_in_emitted_rows`. +The QC JSON accounts for every input read, reporting total FASTQ records, full-length assignments, +gapped rescue assignments (`reads_assigned_gapped`), partial reads credited, ambiguous reads, +unassigned reads, reads absorbed in each denoising pass, reads dropped in low-evidence sequences, and +per-sample `reads_in_emitted_rows`. + +A read credited to multiple tiled markers is counted once in `reads_assigned_full_length` +(`reads_assigned` per sample), while additional tile credits are tracked separately under +`tile_extra_credits_full_length` and `tile_extra_credits_partial` (`tile_extra_credits` and +`partial_tile_extra_credits` per sample). From assignment onward, the accounting ledger tracks +`(marker, read)` credits across `reads_n_mapped`, `reads_n_dropped`, `partial_reads_added_to_counts`, +`reads_in_final_count_table`, denoising transfers, and `reads_in_emitted_rows`. On panels without +tiled markers, credits and reads are identical. The ledger satisfies: + +``` +reads_in_final_count_table = reads_assigned_full_length + tile_extra_credits_full_length + − reads_n_dropped + partial_reads_added_to_counts +``` diff --git a/docs/src/reference/faq.md b/docs/src/reference/faq.md index 53284db..1a82308 100644 --- a/docs/src/reference/faq.md +++ b/docs/src/reference/faq.md @@ -4,53 +4,64 @@ ### Do I need a vendor MADC to run MADCATS? -No. Generation uses only the FASTQs plus the assay design. A vendor MADC can be used afterwards +No. Generation uses only the FASTQs plus the assay design. You can use a vendor MADC afterwards with `madcats validate`, or to bootstrap a panel when the design files are private (`scripts/madc_to_reference_tags.py`). ### Does MADCATS reproduce the vendor's MADC exactly? No, and it does not try to. MADCATS is an independent implementation. Canonical-row counts agree -closely (count r = 0.9997 on sweetpotato), while the novel-row lists differ: many vendor rows have -too little support in the project's own reads to pass any within-project evidence route. See -[Validation & Accuracy](validation.md). +closely (count r = 0.9997 on sweetpotato). The novel-row lists differ, because many vendor rows +have too little support in the project's own reads to pass any within-project evidence route. +See [Validation & Accuracy](validation.md). ### What dependencies does it need? -None beyond Python 3.9+. The standalone binaries need nothing at all. +None beyond Python 3.9+, and the standalone binaries require no Python installation at all. Only +the optional, experimental [`filter-paralogs`](../commands/filter-paralogs.md) command requires +`mappy`, installed via `pip install 'madcats[genome]'`. + +### My vendor MADC has negative read counts + +Some vendor MADCs store counts in a signed 8-bit field. Counts of 128–255 appear as the count minus +256 (so −128 to −1), and counts of 256 or more wrap silently to small positive numbers. The lettuce +3K delivery has 90,913 negative cells across 1,108 markers, and its largest count is 127. +Adding 256 to the negatives recovers the 128–255 band, but nothing tells the wrapped larger counts +from real small ones. `validate` and `filter-paralogs` warn and record this in their reports +but use the counts as stored. Regenerate the table from the FASTQs with `madcats generate`, or ask +the vendor for a corrected file. ## Running ### My run stopped saying reads carry a constant prefix. What do I do? -You have a raw DArT delivery: an inline barcode and the common sequence `GATGGATCCAGTGC` precede -every amplicon. Re-run with `--leading-anchor auto`, or pass the sequence the message names. +You have a raw DArT delivery, in which an inline barcode and the common sequence `GATGGATCCAGTGC` +precede every amplicon. Re-run with `--leading-anchor auto`, or pass the sequence the message names. ### Should I trim adapters first? -No. Reads are located from the middle out, windows stay inside the amplicon, and `merge-pairs` drops +No. MADCATS locates reads from the middle out, windows stay inside the amplicon, and `merge-pairs` drops adapter read-through as part of merging. Trimming changed concordance by 0.05 points on the capture benchmark while costing 2 points of extraction. ### Can I split a large cohort into batches? -Batch `normalize-reads` freely, but run **one** `generate` over every sample. The reproducibility +Batch `normalize-reads` freely, but run one `generate` over every sample. The reproducibility route counts supporting samples within the run, so splitting a cohort into batches finds fewer new -alleles. Use `--cache-dir` to -make re-runs cheap. +alleles. Use `--cache-dir` to make re-runs cheap. ### How many workers should I use? -`--jobs` sets the number of samples processed in parallel (default: up to 4). Each worker processes -one sample at a time, so memory scales with `--jobs`. The finalisation (denoising) stage also runs -across the workers. +`--jobs` sets the number of samples processed in parallel (up to 4 by default). Because each worker +handles one sample at a time, memory usage scales with `--jobs`. The finalization (denoising) stage +also runs in parallel across workers. ### Re-running is slow. Can I reuse earlier work? -Pass `--cache-dir`. Per-sample assignment results are cached and keyed by the read-assignment -settings, so changing evidence, denoising or output options regenerates from cache in a fraction of -the time. Changing an assignment setting (identity, anchor, gapped alignment, partial-read length, tag -length) rebuilds the affected caches. +Pass `--cache-dir`. MADCATS caches per-sample assignment results and keys them by the +read-assignment settings, so a change to evidence, denoising or output options regenerates from +cache in a fraction of the time. A change to the panel, tag length, identity, anchor, primer +mismatches, gapped alignment, partial-read length or tile families starts new caches. ## Panels @@ -62,16 +73,16 @@ primer-free inference only when neither is available. See ### Why do some canonical rows have zero counts? -Two common reasons: the locus differs from the design in your germplasm, or the vendor's curated -tag contains an IUPAC ambiguity code. Rows and counts use exact sequence equality, so an -ambiguity-coded canonical never matches a concrete read; the reads appear in RefMatch/AltMatch rows -instead. +Two common reasons are that the locus differs from the design in your germplasm, or that the +vendor's curated tag contains an IUPAC ambiguity code. Rows and counts use exact sequence equality, +so an ambiguity-coded canonical never matches a concrete read, and the reads appear in +RefMatch/AltMatch rows instead. ### What is `--reuse-tags` for, and when do I need it? -For `normalize-reads` panels only. Window placement is learned from coverage, so it can shift -between runs and make identical biology look like new haplotypes. Pass the first run's window CSV -to every later run of the same panel. +For `normalize-reads` panels only. `normalize-reads` learns window placement from coverage, so +placement can shift between runs and make identical biology look like new haplotypes. Pass the first +run's window CSV to every later run of the same panel. ## Discovery @@ -82,8 +93,8 @@ sample per marker even sequencing errors can pass them. Add `--min-supporting-fr ### How do I get only SNP microhaplotypes? -Filter on the `MarkerType` column: drop `indel` and `both` rows. Designed indel markers stay -intact. +Filter on the `MarkerType` column and drop `indel`, `both` and `unresolved` rows. Designed indel +markers stay intact. ### How do I get the exact vendor header? @@ -97,5 +108,6 @@ Generate with `--dart-preamble`. HapApp expects the vendor's starred preamble ro ### Where did a sample's reads go? -`OUTPUT.qc.json` accounts for every read per sample: assigned, ambiguous, without the leading -anchor, too short, moved by denoising, dropped with low-evidence sequences, and in emitted rows. +`OUTPUT.qc.json` accounts for every read per sample. It counts the reads assigned, ambiguous, +without the leading anchor, too short, moved by denoising, dropped with low-evidence sequences, +and in emitted rows. diff --git a/docs/src/reference/output-formats.md b/docs/src/reference/output-formats.md index 8d861a5..0fe98ed 100644 --- a/docs/src/reference/output-formats.md +++ b/docs/src/reference/output-formats.md @@ -3,7 +3,7 @@ ## MADC Table `madcats generate --output` writes a CSV with one row per allele and one integer read-count column -per sample. Rows are grouped by marker and ordered Ref, Alt, RefMatch, AltMatch, Other. +per sample. It groups rows by marker and orders them Ref, Alt, RefMatch, AltMatch, Other. ``` AlleleID,CloneID,AlleleSequence,ClusterConsensusSequence,CallRate,...,RatioAvgCountRefAvgCountSnp,4404001,4404002,... @@ -16,51 +16,89 @@ Chr01_000123|RefMatch,Chr01_000123,ACGT...,ACGT...,0,...,.,57,0,... | Column | Contents | |--------|----------| -| `AlleleID` | Marker name and category joined by a pipe, e.g. `Chr01_000123\|AltMatch`. With `--number-match-ids`, Match/Other rows get a stable serial: `Chr01_000123\|RefMatch_0001` | +| `AlleleID` | Marker name and category joined by a pipe, e.g. `Chr01_000123\|AltMatch`. With `--number-match-ids`, Match/Other rows get a stable serial, such as `Chr01_000123\|RefMatch_0001` | | `CloneID` | Marker name | -| `AlleleSequence` | The row's tag sequence | -| `ClusterConsensusSequence` | Canonical rows carry their own sequence; Match/Other rows carry the Ref tag, following vendor convention | -| `CallRate` | Canonical rows: fraction of samples with canonical Ref or Alt reads at the locus. Other rows: `0` | -| `OneRatioRef` … `PICRef` | Vendor downstream statistics, not FASTQ evidence: emitted as `.` | -| `PICSnp` → **`Variants`** | With `--annotations on` (default): the row's events against the Ref tag. Otherwise `.` | -| `AvgPIC` → **`MarkerType`** | With `--annotations on` (default): what the row carries beyond its canonical. Otherwise `.` | -| `AvgCountRef`, `AvgCountSnp` | Canonical rows: nonzero means of the Ref and Alt counts. Other rows: the row's own nonzero mean, in both columns | +| `AlleleSequence` | The row's tag sequence. With `--remove-primers on`, the tag without its primers | +| `ClusterConsensusSequence` | Canonical rows carry their own sequence. Match/Other rows carry the Ref tag (the Ref row's sequence), following vendor convention | +| `CallRate` | For canonical rows, the fraction of samples with canonical Ref or Alt reads at the locus. For other rows, `0` | +| `OneRatioRef` … `PICRef` | Vendor downstream statistics, not FASTQ evidence, so emitted as `.` | +| `PICSnp` → `Variants` | With `--annotations on` (default), the row's events against the Ref tag. Otherwise `.` | +| `AvgPIC` → `MarkerType` | With `--annotations on` (default), what the row carries beyond its canonical. Otherwise `.` | +| `AvgCountRef`, `AvgCountSnp` | For canonical rows, nonzero means of the Ref and Alt counts. For other rows, the row's own nonzero mean, in both columns | | `RatioAvgCountRefAvgCountSnp` | `.` | | one column per sample | Integer read counts | -Sample columns are named by the FASTQ stem (or a unique `--sample-name-field` from target -manifests), or renamed with `--sample-lookup`. +MADCATS names sample columns by the FASTQ stem (or a unique `--sample-name-field` from target +manifests), or `--sample-lookup` renames them. ### Annotations `--annotations on` (the default) repurposes two statistics columns the pipeline never computes. The -column *positions* are unchanged, so positional consumers see the same 16-column layout. +column *positions* stay the same, so positional consumers see the same 16-column layout. `--annotations off` restores the exact vendor header and writes no sidecar. -**`MarkerType`** says what the row carries beyond its canonical: +**`MarkerType`** summarizes what variants a row carries beyond its canonical allele: | Value | Meaning | |-------|---------| -| `.` | The Ref row, or a row that only realises an ambiguity code | +| `.` | The Ref row, or a row that only realizes an IUPAC ambiguity code | | `snp` | Substitutions only (the Alt row of a designed SNP is `snp`) | | `indel` | Gaps only (the Alt row of a designed indel is `indel`) | -| `both` | Substitutions and gaps | +| `both` | Both substitutions and gaps | +| `unresolved` | The trailing end of the row is unread (`unresolved=k` in `Variants`), regardless of earlier events, because a trailing gap is likely but unverified | -To keep SNP-only microhaplotypes, drop `indel` and `both` rows by this label. +To retain SNP-only microhaplotypes downstream, filter out `indel`, `both`, and `unresolved` rows +using this column. -**`Variants`** lists the row's events against the Ref tag, `;`-separated, in 1-based coordinates on -the tag as printed: +**`Variants`** lists each row's variant events relative to the Ref tag, separated by `;`, in 1-based +coordinates on the printed sequence. Events come from the same alignment that assigned the row's +category, so both columns report the same base at the target position. When `--remove-primers on` +produces a trimmed row whose length differs from the trimmed Ref row, `generate` realigns the +trimmed sequences for annotation, which can shift secondary event representation while keeping the +original classification and target base. | Token | Meaning | |-------|---------| | `91:A>T` | Substitution | -| `55:C>CAAAA` | Insertion, VCF-anchored on the preceding reference base, left-normalised | +| `55:C>CAAAA` | Insertion, VCF-anchored on the preceding reference base and left-normalized | | `70:TAG>T` | Deletion | -| `clip=4` | An insertion pushed the last 4 Ref bases out of the window | -| `overhang=3` | A deletion pulled 3 downstream bases into the window | - -Example: `55:C>CAAAA;91:A>T;clip=4`. The Ref row is `.`; the Alt row of a designed SNP is exactly the -design (e.g. `46:C>G`). +| `clip=4` | An upstream insertion pushed the last 4 Ref bases past the window end | +| `overhang=3` | An upstream deletion pulled 3 downstream bases into the window | +| `unresolved=9` | The last 9 Ref bases are unread because the trailing end could reflect either a gap or substitutions ([Classification](evidence-model.md#classification)). Always appears last | +| `1:.>GG`, `1:TT>.` | An insertion before base 1, or a deletion starting at base 1, with no preceding anchor base (`.` represents empty sequence: `GG` inserted before base 1, or bases 1–2 `TT` deleted) | +| `31:G>A;32:CACG>.`, `31:G>A;32:.>TT` | An insertion or deletion immediately following a substituted base, leaving no unmodified anchor base (bases 32–35 deleted, or `TT` inserted before base 32) | + +For example, `55:C>CAAAA;91:A>T;clip=4` describes an insertion at position 55, a SNP at position 91, +and 4 clipped trailing Ref bases. The canonical Ref row is `.`, and the Alt row of a designed SNP +matches the assay design (e.g., `46:C>G`). + +Each `position:REF>ALT` token specifies replacing `REF` with `ALT` starting at that 1-based Ref +position. `clip=k` removes the final `k` Ref bases, `overhang=k` appends the row's final `k` bases, +and `unresolved=k` removes the final `k` Ref bases before appending the remaining observed suffix. +Because no two tokens overlap on the same Ref base, applying them sequentially reconstructs the +exact printed row sequence from the Ref tag. + +For designed indel markers, `generate` annotates all rows against the Ref tag using gapped alignment +and counts any unresolved suffix in Ref coordinates. A designed indel does not resolve a separate +unverified gap near the end of the row. + +A row carrying `unresolved=k` makes no call on Ref positions from `length - k + 1` onward (neither a +variant nor a reference match). Downstream scripts aggregating per-position counts should exclude +the row's reads in that suffix just as they do for `clip`, and parsers encountering an unfamiliar +token should not infer calls directly from the raw sequence. + +With `--remove-primers on`, coordinates are measured on the trimmed Ref sequence, with position 1 at +the first base after the left primer. `generate` still decides whether to use a gapped alignment on +the full untrimmed tag, and any trimmed row whose length differs from the trimmed Ref row is always +aligned with gaps. When both the Ref row and a given row are cut at their right primer, they are +compared end to end so trailing differences are represented as indels rather than `clip` or +`overhang`. All other trimmed rows represent fixed-length windows and retain `clip` and `overhang`. +If a row's trimmed length differs from the Ref row by more than `--max-indel-length`, it is compared +base by base from the start with the remainder recorded as `clip` or `overhang`. + +A trimmed row preserves the `unresolved=k` suffix from its full-tag alignment (recounted in trimmed +Ref coordinates), omitting the token only if the entire unresolved stretch lay inside the removed +right primer. ## Variants Sidecar @@ -72,51 +110,75 @@ design (e.g. `46:C>G`). | `CloneID`, `AlleleID`, `AlleleSequence` | Row identity | | `Position` | 1-based position on the Ref tag | | `Ref`, `Alt` | Event alleles | -| `Type` | `snp`, `ins`, `del`, `clip` (Ref holds the unobserved bases) or `overhang` (Alt holds the pulled-in bases) | +| `Type` | `snp`, `ins`, `del`, `clip` (Ref holds the unobserved bases), `overhang` (Alt holds the pulled-in bases) or `unresolved` (Position is the first Ref base not read, Ref the Ref bases from it on, Alt the row's bases that stand there) | ## QC / Provenance JSON `OUTPUT.qc.json` records: - the pipeline version and every parameter - input paths -- per-sample read accounting: records read, reads assigned, gapped and partial assignments, reads +- per-sample read accounting of records read, reads assigned, gapped and partial assignments, reads in emitted rows, reads moved by denoising, reads dropped and why +- the tile families (`tile_families`) and the extra credits they add (`tile_extra_credits_*`, + described in [Read Accounting](evidence-model.md#read-accounting)) - row counts by category, by evidence route, and by `marker_types` +- `unresolved_ends`: the rows with an unread end and their reads, and how many of them have the + target in that end (those rows are `Other`). `generate` counts them on the full tags, so the + figures do not depend on `--remove-primers` or `--annotations` +- `read_continuation`: how many bases after the tag `generate` compared (`bases_after_tag`, 0 when + reads end at the tag), and the rows and reads whose unread target they settled + ([Classification](evidence-model.md#classification)) - the variants sidecar path +- with `--remove-primers on`, `primer_removal`: the panel's amplicon length, the markers by whether + `generate` located their right primer (and if not, why), and the rows merged, cut at their right + primer, or keeping it + +`normalize-reads`, `infer-design`, `window-scan` and `filter-paralogs` write their own QC JSONs. See +each command's page. + +## Genome Labels (filter-paralogs) + +[`madcats filter-paralogs`](../commands/filter-paralogs.md) writes a filtered copy of any MADC. It +copies kept rows unchanged. In flag mode (`--paralogs flag` or `--ambiguous flag`) it repurposes a +third statistics column, keeping the 16-column layout: + +| Column | Contents | +|--------|----------| +| `PICRef` → `GenomeLabel` | `on_target`, `paralog`, `ambiguous`, `unmapped` or `unplaced`, depending on where the reference genome places the row's haplotype | -`normalize-reads`, `infer-design` and `window-scan` write their own QC JSONs; see each command's page. +It also writes `OUTPUT.genome_labels.csv`, with one line per input row (dropped rows included), +and `OUTPUT.genome_markers.csv`, with where it placed each marker. The command page describes both. ## Vendor-Style Preamble (HapApp) `--dart-preamble` prepends the seven starred rows that vendor raw MADCs carry above the header, so preamble-expecting consumers such as HapApp and HapApp_utils accept the file: -1. service/project label (`--preamble-project`, default: output filename before its first dot) +1. service/project label (`--preamble-project`, by default the output filename before its first dot) 2. plate barcode 3. plate number 4. plate row 5. plate column 6. plate name -7. `targetid`: the FASTQ-derived sample ids, directly above the header's sample names +7. `targetid`, the FASTQ-derived sample ids, directly above the header's sample names Every empty preamble cell is `*`, as in vendor output. The file's first cell holds a full provenance string (pipeline, version, and every generation parameter as `key=value`), prefixed with -`* ` so consumers that skip starred lines still skip it. No timestamp is included, so output stays -byte-reproducible. +`* ` so consumers that skip starred lines still skip it. The file has no timestamp, so the output +is byte-reproducible. Combine with `--sample-lookup` to rename sample columns while the targetid row keeps the FASTQ ids, matching the raw vendor layout. ## Downstream Processing -A MADCATS table is a raw MADC. Its allele IDs are per-project (`|RefMatch`, `|AltMatch`, ...) and -are not yet matched to the panel's fixed allele IDs. Run it through HapApp or HapApp_utils -(generate with `--dart-preamble`) before using it in BIGr, updog or other downstream tools. HapApp -assigns the fixed allele IDs and maintains the panel's cross-project allele database; MADCATS does -neither. +A MADCATS table is a raw MADC. Its allele IDs are per-project (`|RefMatch`, `|AltMatch`, ...), not +the panel's fixed allele IDs. Run it through HapApp or HapApp_utils (generate with `--dart-preamble`) +before using it in BIGr, updog or other downstream tools. HapApp assigns the fixed allele IDs and +keeps the panel's cross-project allele database. MADCATS does neither. polyRAD's `readDArTag` is one example. In polyRAD 2.0.1 it rejects raw MADCs, from MADCATS or the -vendor: Match rows share allele IDs, and the statistics columns are read as samples. It does read +vendor: Match rows share allele IDs, and it reads the statistics columns as samples. It does read the processed layout (unique allele IDs, then `AlleleID`, `CloneID`, `AlleleSequence` and the sample columns). @@ -130,5 +192,5 @@ them later. ## Format References -- Breeding Insight: [MADC file format](https://breeding-insight.github.io/BIGr_documentation/posts/madc-file-format/) -- Breeding Insight: [MADC data processing](https://breeding-insight.github.io/BIGr_documentation/posts/madc-data-processing/) +- [MADC file format](https://breeding-insight.github.io/BIGr_documentation/posts/madc-file-format/) from Breeding Insight +- [MADC data processing](https://breeding-insight.github.io/BIGr_documentation/posts/madc-data-processing/) from Breeding Insight diff --git a/docs/src/reference/validation.md b/docs/src/reference/validation.md index 98fb972..92bc54c 100644 --- a/docs/src/reference/validation.md +++ b/docs/src/reference/validation.md @@ -10,17 +10,17 @@ version-to-version comparison, is in the [development record](https://github.com loss is off-target and primer-dimer reads that should be rejected, and other pipelines calculate their percentages differently. -"Genotype agreement" means the MADCATS table was run through HapApp, BIGr and updog to call dosages, +"Genotype agreement" means the MADCATS table went through HapApp, BIGr and updog to call dosages, and those calls were compared with the reference genotypes. | Platform (dataset) | Reads → usable windows | Accuracy | Validated against | |---|---|---|---| -| DArTag (sweetpotato, red clover, blackberry, alfalfa, pecan) | 56.5% of delivered records, vs the vendor's 50.9% on the same FASTQs | Sweetpotato count r = 0.9997 (1.20M cells); red clover dosage agreement 96.98%; blackberry 95.39%; alfalfa 98.40% / 97.40%; pecan 98.78% | Vendor MADC, vendor/updog dosage, families, skim-seq VCF | -| AgriSeq, Ion Torrent (2 honeybee chips; 372-sample oyster) | 88.4% | 94.9% vs Torrent VariantCaller (152,698 cells); honeybee replicate concordance 98.0% | Vendor caller + replicates | -| GT-seq (96-sample delta smelt) | 84.5% merged | 99.49% R1-only; 98.42% genotype agreement; `infer-design` 368/368 | Independent BWA/bcftools truth VCF | -| Flex-Seq capture (192-sample cranberry) | 81.9% | 95.13% genotype agreement (295,068 cells); trio incompatibility 3.6% vs 6.2% for the comparison VCF's source | Published population VCF + 20 pedigree trios | -| rhAmpSeq (608 runs, 8 grape families) | 86.6% | Family transmission 99.92–99.99%; 93.0% exact agreement with the platform's pipeline | -| Synthetic truth suite | — | Dosage 100% on clean, linked, paralog and repeat classes; paired-end merge 100% with 98.6% molecular recovery | Exact simulated truth | +| DArTag (sweetpotato, red clover, blackberry, alfalfa, pecan) | 56.5% of delivered records, vs the vendor's 50.9% on the same FASTQs | Sweetpotato count r = 0.9997 (1.20M cells), red clover dosage agreement 96.98%, blackberry 95.39%, alfalfa 98.40% / 97.40%, pecan 98.78% | Vendor MADC, vendor/updog dosage, families, skim-seq VCF | +| AgriSeq, Ion Torrent (2 honeybee chips, 372-sample oyster) | 88.4% | 94.9% vs Torrent VariantCaller (152,698 cells) and honeybee replicate concordance 98.0% | Vendor caller + replicates | +| GT-seq (96-sample delta smelt) | 84.5% merged | 99.49% R1-only, 98.42% genotype agreement, `infer-design` 368/368 | Independent BWA/bcftools truth VCF | +| Flex-Seq capture (192-sample cranberry) | 81.9% | 95.13% genotype agreement (295,068 cells) and trio incompatibility 3.6% vs 6.2% for the comparison VCF's source | Published population VCF + 20 pedigree trios | +| rhAmpSeq (608 runs, 8 grape families) | 86.6% | Family transmission 99.92–99.99%, and 93.0% exact agreement with the platform's pipeline | Mendelian constraints + same-reads head-to-head | +| Synthetic truth suite | — | Dosage 100% on clean, linked, paralog and repeat classes, and paired-end merge 100% with 98.6% molecular recovery | Exact simulated truth | Accuracy depends more on the quality of the comparison data than on the platform. Where the reference genotypes are reliable (GT-seq, DArTag), MADCATS agrees at 98–99% or better. Against @@ -31,8 +31,8 @@ checks show the MADCATS calls to be the more consistent of the two. ### Sweetpotato (hexaploid, 81-bp tags) -The development project: 80 samples, 3,120 markers, 154.6M reads. Against the vendor MADC (19,319 -rows), every shared row had identical classification. +The development project has 80 samples, 3,120 markers and 154.6M reads. Against the vendor MADC +(19,319 rows), every shared row had identical classification. | Configuration | Rows | Precision | Recall | |---|---|---|---| @@ -40,63 +40,65 @@ rows), every shared row had identical classification. | `--reproducible-min-reads 20` | 16,517 | 89.8% | 76.8% | | `--min-supporting-freq 0.01` | 17,319 | 86.2% | 77.2% | -Row recall against a vendor table has a ceiling: 27.3% of the vendor's positive-count rows have +Row recall against a vendor table has a ceiling. 27.3% of the vendor's positive-count rows have fewer than 10 reads in fewer than 2 samples of the vendor's own counts, below any within-project evidence threshold. ### Red clover (diploid, 109-bp tags, ~60x depth, no primer file) -- `infer-design` recovered 2,968 loci; 2,902 exactly match the vendor canonicals and 56 differ only - by vendor IUPAC curation. -- Recall against vendor rows with enough read support to pass an evidence route: 94.1%. -- Updog dosage concordance with the vendor-derived calls: 99.73% at DP ≥ 10. +- `infer-design` recovered 2,968 loci, of which 2,902 exactly match the vendor canonicals and 56 + differ only by vendor IUPAC curation. +- Recall against vendor rows with enough read support to pass an evidence route was 94.1%. +- Updog dosage concordance with the vendor-derived calls was 99.73% at DP ≥ 10. - In a 152-progeny mapping family, the Mendelian-violation rate was 1.30% under MADCATS against - 1.59% under the vendor MADC. The heterozygotes created by recovered indel alleles are inherited. + 1.59% under the vendor MADC. The progeny inherit the heterozygotes created by recovered indel + alleles. ### Blackberry (mixed ploidy, 109-bp tags, indels, degenerate primers) The first project validated through all three panel routes: -- Design files: 2,881 / 3,015 exact; all 134 others differ only by vendor IUPAC codes; all 10 - indel loci exact. -- Vendor-MADC bootstrap: 92.9% precision, and 94.7% recall against vendor rows with enough read - support to pass an evidence route. -- Primer-free inference: 2,943 inferred; 18 wrong windows (0.6%), all at read-starved or +- With design files, 2,881 / 3,015 were exact, all 134 others differ only by vendor IUPAC codes, + and all 10 indel loci were exact. +- The vendor-MADC bootstrap gave 92.9% precision, and 94.7% recall against vendor rows with enough + read support to pass an evidence route. +- Primer-free inference returned 2,943 with 18 wrong windows (0.6%), all at read-starved or short-amplicon loci. ### Alfalfa and pecan (raw deliveries) -- Alfalfa (two 2021 orders, 54-bp design): category agreement 99.60% / 99.83%, dosage agreement - 98.40% / 97.40%; F1 and BC1 progeny haplotypes within the parental sets at 98.6–98.7% (vendor - 98.9%). -- Pecan 3K (81-bp design): category agreement 98.89%, dosage agreement 98.78% on 1.02M cells; F1 - progeny within the parental set at 99.82% (vendor 99.86%); 93.3% agreement with skim-sequencing - genotypes on 11 shared cultivars (vendor 93.3%). +- Alfalfa (two 2021 orders, 54-bp design) had category agreement of 99.60% / 99.83% and dosage + agreement of 98.40% / 97.40%. F1 and BC1 progeny haplotypes fell within the parental sets at + 98.6–98.7% (vendor 98.9%). +- Pecan 3K (81-bp design) had category agreement of 98.89% and dosage agreement of 98.78% on 1.02M + cells. F1 progeny fell within the parental set at 99.82% (vendor 99.86%), and agreement with + skim-sequencing genotypes on 11 shared cultivars was 93.3% (vendor 93.3%). ## AgriSeq (Ion Torrent) -- Honeybee: two chips on an 81-marker panel. The curated frozen 41-bp panel scored 93.4% / +- Honeybee used two chips on an 81-marker panel. The curated frozen 41-bp panel scored 93.4% / 93.9% vendor-caller concordance and 98.0% concordance across 30 technical replicate pairs. Freezing windows raised cross-chip haplotype sharing from 42% to 88%. -- Pacific oyster (PRJNA1118744; 372 samples, 591 amplicons): with the honeybee defaults - unmodified, 88.4% of reads normalized and genotypes agreed with Torrent VariantCaller at 94.9%, - on a different lab, species, chip generation and target length. +- In Pacific oyster (PRJNA1118744, 372 samples, 591 amplicons), the honeybee defaults, unchanged, + normalized 88.4% of reads, and genotypes agreed with Torrent VariantCaller at 94.9%. Lab, + species, chip generation and target length all differ from honeybee. ## GT-seq (delta smelt, Zenodo 10.5281/zenodo.19069550) -96 samples, 410 loci, and the panel's real primer file. Genotypes agreed with the archive's +The run used 96 samples, 410 loci, and the panel's real primer file. Genotypes agreed with the archive's independent BWA/bcftools VCF at 99.49%. Merged reads with frozen tags plus tiles kept that accuracy on the original markers while adding 54% more truth-validated calls. `infer-design` with the primer file withheld recovered 368/368 loci exactly. ## Flex-Seq Capture (cranberry) -192 samples with a K=4 tiled 110-bp panel and one cohort-level `generate`. Genotype agreement with +The benchmark used 192 samples with a K=4 tiled 110-bp panel and one cohort-level `generate`. +Genotype agreement with the published population VCF was 95.13%. Trio incompatibility was 3.6%, against 6.2% for the raw calls behind the comparison VCF. ## rhAmpSeq (grape, PRJNA281110) -Eight biparental families (763 runs) processed against one frozen 2,951-window panel. Across +MADCATS processed eight biparental families (763 runs) against one frozen 2,951-window panel. Across ~14,900 locus-family tests, 99.92–99.99% of haplotype calls in every family are alleles of that locus's four inferred parental haplotypes. @@ -105,3 +107,33 @@ locus's four inferred parental haplotypes. Across 127,667 emitted rows in six MADCs spanning five platforms, zero rows contain TruSeq or Ion P1 adapter at a strict 13-mer probe. Trimming adapters before a run changed dosage concordance by 0.05 points on the capture benchmark while costing 2 points of extraction. + +## Genome Paralog Filter (`filter-paralogs`) + +- **Lettuce 3K DArTag (development benchmark).** Keep/drop decisions agreed with bwa-mem on 98.2% + of rows in a MADCATS MADC and 94.9% of rows in a vendor MADC (97.3% and 94.8% among rows the + filter actively decides). Against blastn on a sample of 18,763 vendor rows, decisions agreed on + 99.4–99.6% of rows dropped as `paralog` and on 69% of well-supported kept rows (89% of their + reads). Kept rows that blastn would drop lie far from the reference and account for ~1% of kept + reads. +- **Delta smelt GT-seq (marker placement).** `filter-paralogs` placed all 368 markers at the exact + sites matching their physical primers in the 437 Mb reference genome and dropped zero rows on this + paralog-free panel. +- **Delta smelt GT-seq (planted paralog copies).** Synthetic paralogous copies of 105 marker tags + were inserted into the reference genome and corresponding haplotype rows were added to the MADC. + `filter-paralogs` labeled 450 of 450 rows derived from copies carrying 1–8 substitutions or a + 2 bp deletion as `paralog`, while dropping 0 of 3,348 rows from unmodified markers. (Copies absent + from the reference genome cannot be detected.) +- **Alfalfa 3K DArTag (design genome).** Across two tetraploid F1 families and the panel haplotype + database aligned to chromosome set 1 of XinJiangDaYe, `filter-paralogs` placed every marker at its + CloneID coordinate and agreed with bwa-mem on 99.7–99.9% of rows and with blastn on 99.4–99.7%. +- **Alfalfa 3K DArTag (genetic inheritance).** Evaluated by genetic linkage mapping in both + families, 96% of kept rows mapped to their own marker locus, while 91–94% of scorable `paralog` + rows mapped elsewhere in the genome. On this panel, the filter removes only ~3% of reads (compared + with 63% in lettuce) and leaves target genotypes unchanged. +- **Alfalfa 3K DArTag (multi-haplotype reference).** Including a second chromosome set of the design + assembly caused `filter-paralogs` to drop 1,969 of 2,753 RefMatch and AltMatch rows compared with + 296 on a single chromosome set. Haplotype-resolved or autopolyploid assemblies must therefore be + reduced to one chromosome set before indexing. + +See [`filter-paralogs`](../commands/filter-paralogs.md#limitations) for full limitations. diff --git a/docs/src/tutorials/agriseq.md b/docs/src/tutorials/agriseq.md index e810692..6881d3b 100644 --- a/docs/src/tutorials/agriseq.md +++ b/docs/src/tutorials/agriseq.md @@ -6,10 +6,11 @@ AgriSeq reads (Ion Torrent) break the primer-started model three ways: - primer digestion, and primers placed outside the submitted targets, scatter read start positions - Ion Torrent's dominant error is the homopolymer indel -`madcats normalize-reads` adapts such reads. It locates each read against the probe-design targets -by k-mer, orients it forward, and excises a fixed-length window containing the variant. The output -is a folder of pipeline-ready per-sample FASTQs plus a matching window reference-tags CSV. After -that, `generate` runs unchanged. +`madcats normalize-reads` converts these variable-start reads into the standardized format required +by `generate`. Using a k-mer lookup table built from the probe-design targets, it locates each read, +re-orients it to the forward strand, and excises a fixed-length window containing the target +variant. This produces a folder of normalized per-sample FASTQs and a matching window reference-tags +CSV, after which `generate` runs without modification. ## First Run of a Panel @@ -34,16 +35,16 @@ madcats generate \ context. Use [`window-scan`](../commands/window-scan.md) to choose a length for a new panel. - `--min-supporting-freq 0.10` is the recommended setting for AgriSeq. At AgriSeq depths (hundreds of reads per sample per marker), even sequencing errors pass the absolute read thresholds. On - honeybee, default evidence admitted 1,752 novel rows, about 92% of them error haplotypes; the - frequency floor brought that down to 147 while improving caller concordance. + honeybee, default evidence admitted 1,752 novel rows, about 92% of them error haplotypes, and + the frequency floor brought that down to 147 while improving caller concordance. ### Window placement -With `--window-placement auto` (the default), each marker's window is placed from observed read -coverage, keeping the variant out of the assignment anchor and steering off tandem repeats -(`--str-penalty`). Repeats matter: when a variant allele lengthens an adjacent repeat, reads -carrying that allele are lost more often in a window that spans the repeat, and the marker can -look monomorphic. +With `--window-placement auto` (the default), MADCATS places each marker's window from observed +read coverage, keeping the variant out of the assignment anchor and steering off tandem repeats +(`--str-penalty`). Repeats matter. When a variant allele lengthens an adjacent repeat, a window +that spans the repeat loses reads carrying that allele more often, and the marker can look +monomorphic. ## Every Later Run: Freeze the Windows @@ -56,15 +57,15 @@ madcats normalize-reads \ --jobs 8 ``` -Windows are placed from each run's own reads. Re-learning placement per run moved 42 of 85 +MADCATS places windows from each run's own reads. Re-learning placement per run moved 42 of 85 windows between two honeybee chips, which made 58% of the second chip's haplotypes falsely appear new. Freezing with `--reuse-tags` raised cross-chip haplotype sharing from 42% to 88%. With `--reuse-tags`, `normalize-reads` still scores the frozen windows against the new run's reads -and reports `freeze_health` in the QC: the read-weighted coverage of the frozen panel against what -fresh placement would choose today, and the markers losing the most. One line on stderr summarizes -what freezing costs this run. +and reports `freeze_health` in the QC. It records the read-weighted coverage of the frozen panel +against what fresh placement would choose today, and the markers losing the most. One line on +stderr summarizes what freezing costs this run. ## Recommended Production Workflow @@ -85,5 +86,5 @@ at the minimum and 209 grown to 13–32 bp. ## Other Platforms The same route handles any amplicon or capture platform whose reads contain a panel window but do -not start at a fixed primer. For paired-end data, decide the geometry first; see +not start at a fixed primer. For paired-end data, decide the geometry first. See [Paired-End Reads and Tiling](paired-end.md). diff --git a/docs/src/tutorials/dartag.md b/docs/src/tutorials/dartag.md index 33d3ca6..ea782a9 100644 --- a/docs/src/tutorials/dartag.md +++ b/docs/src/tutorials/dartag.md @@ -25,13 +25,13 @@ madcats design \ --output sweetpotato_reference_tags.csv ``` -For each marker, `design` locates the left primer in the target sequence (either orientation), -extracts the primer-started tag that carries the bracketed variant, verifies the variant position, -and builds the Alt tag. If the design files disagree with each other, the run stops with an error. +For each marker, `design` locates the left primer in the target sequence (either orientation) and +extracts the primer-started tag that carries the bracketed variant. It then checks the variant +position and builds the Alt tag. If the design files disagree with each other, the run stops with an error. -Open the CSV and check it: one row per marker with `RefSequence` and `AltSequence` of the tag -length. This file is now the panel. You can hand it to collaborators or use it on later orders -without the vendor files. +Open the CSV and check that it has one row per marker, with `RefSequence` and `AltSequence` of +the tag length. This file is now the panel. You can hand it to collaborators or use it on later +orders without the vendor files. ## 2. Generate the MADC @@ -46,22 +46,23 @@ madcats generate \ What happens, in order: -1. Each read is assigned to a marker by its left-primer prefix (one mismatch allowed by default). -2. The fixed-length tag is kept and accepted if it is within 80% identity of the marker's Ref or - Alt tag. Reads that fail get one more try with a gapped alignment, so undesigned indels are - still counted. -3. Reads shorter than the tag are added to the count of a full-length allele whose start they - match exactly. They cannot create a new allele. -4. Canonical Ref and Alt rows are always written. Any other sequence is reported only if it passes - one of the [evidence routes](../reference/evidence-model.md). -5. Rare sequences that differ by one base from a much more common sequence in the same sample are - treated as sequencing errors and merged into it (abundance-skew denoising). +1. MADCATS assigns each read to a marker by its left-primer prefix (one mismatch allowed by + default). +2. It keeps the fixed-length tag and accepts it if it is within 80% identity of the marker's Ref + or Alt tag. Reads that fail get one more try with a gapped alignment, so the counts still + include undesigned indels. +3. Reads shorter than the tag add to the count of a full-length allele whose start they match + exactly. They cannot create a new allele. +4. MADCATS always writes the canonical Ref and Alt rows, and reports any other sequence only if it + passes one of the [evidence routes](../reference/evidence-model.md). +5. A rare sequence one base away from a much more common one in the same sample is a sequencing + error. MADCATS merges it into the common one (abundance-skew denoising). ## 3. Read the QC -`results/sweetpotato_MADC.csv.qc.json` accounts for every read. Look first at the per-sample totals: -samples with very few assignable tags (on the sweetpotato project, twelve samples had fewer than -100,000; the lowest had 23) usually contain mostly short or primer-less reads. Check them for +`results/sweetpotato_MADC.csv.qc.json` accounts for every read. Look first at the per-sample totals. +Samples with very few assignable tags (on the sweetpotato project, twelve samples had fewer than +100,000 and the lowest had 23) usually contain mostly short or primer-less reads. Check them for missing data before using them downstream. ## 4. Optional: Compare with the Vendor MADC @@ -77,9 +78,9 @@ The report gives row precision and recall by allele category plus cell-level cou this project every shared row had identical classification, and shared-cell count correlation was 0.9997. -Do not expect 100% row recall against a vendor table: 27.3% of the vendor's positive-count rows on -this project had fewer than 10 reads in fewer than 2 samples of the vendor's *own* counts, below -any within-project evidence threshold. +Do not expect 100% row recall against a vendor table. On this project 27.3% of the vendor's +positive-count rows had fewer than 10 reads in fewer than 2 samples of the vendor's *own* counts, +below any within-project evidence threshold. ## Tuning @@ -95,10 +96,11 @@ The defaults are the recommendation for diploid and polyploid DArTag projects al ## Raw DArT Deliveries -Older DArT orders deliver reads with an inline barcode and the library's common sequence -`GATGGATCCAGTGC` in front of the amplicon, so nothing is primer-started. MADCATS checks the first -FASTQ before any read pass. When almost no read starts with a panel tag but most carry one after a -constant prefix, the run stops and names that prefix. Re-run with: +Older DArT orders deliver reads with an inline barcode and the common library sequence +`GATGGATCCAGTGC` preceding the amplicon, so the reads do not begin directly at the left primer. +Before running the read pass, MADCATS inspects a sample of up to 24 FASTQ files. If almost no reads +start with a panel tag but most contain one after a constant prefix, the run stops and reports that +prefix. Rerun with `--leading-anchor auto` or pass the sequence explicitly: ```bash madcats generate ... --leading-anchor auto @@ -106,4 +108,11 @@ madcats generate ... --leading-anchor auto madcats generate ... --leading-anchor GATGGATCCAGTGC ``` -Reads without the anchor are counted as `reads_no_leading_anchor` in the QC. +When running on only one or two FASTQ files, the prefix detected by `auto` may include sample +barcode bases. It will work for those files, and MADCATS warns you not to reuse that prefix across +other samples. + +By default, `--leading-anchor-mismatches 0` requires an exact anchor match. Setting +`--leading-anchor-mismatches 1` allows MADCATS to also cut reads whose anchor contains a single +substitution, provided there is only one such placement. The QC JSON tracks these reads under +`reads_leading_anchor_mismatch` and counts reads lacking the anchor as `reads_no_leading_anchor`. diff --git a/docs/src/tutorials/paired-end.md b/docs/src/tutorials/paired-end.md index b2a63cd..4b7620b 100644 --- a/docs/src/tutorials/paired-end.md +++ b/docs/src/tutorials/paired-end.md @@ -1,12 +1,12 @@ # Paired-End Reads and Tiling -MADCATS does not detect paired-end data automatically. Check how the reads of your assay are laid -out and pick the matching route. +MADCATS does not detect paired-end layouts automatically. Check how reads are arranged for your +assay and select the corresponding intake workflow. ## Overlapping Pairs: Merge -When the insert is shorter than R1 + R2 (for example GT-seq PE100 over 130–200-bp amplicons, or -rhAmpSeq), merge first: +When the target fragment is shorter than R1 + R2 (for example, GT-seq PE100 across 130–200 bp +amplicons, or rhAmpSeq), merge the read pairs first: ```bash madcats merge-pairs \ @@ -15,35 +15,42 @@ madcats merge-pairs \ --jobs 8 ``` -The merger reverse-complements R2 and scans overlaps longest first. The merged read is always R1's -head, plus the overlap, plus R2's tail. In read-through geometry, R1's adapter tail past the -fragment end falls outside the overlap and never reaches the merged read, so no adapter trimming -is needed. Disagreeing overlap bases take the higher-quality call. +`merge-pairs` reverse-complements R2 and evaluates candidate overlaps from longest to shortest. The +merged fragment consists of R1's leading bases, the overlap consensus, and R2's trailing bases. When +reads extend past the amplicon into adapter sequence (read-through), the adapter tail falls outside +the overlap and is automatically removed, so no separate adapter trimming is needed. Any base +disagreements within the overlap are resolved by selecting the base with the higher Phred quality +score. -`--unmerged` decides what happens to pairs that do not merge: +`--unmerged` controls how pairs without a valid overlap are handled: -| Value | Behaviour | -|-------|-----------| -| `r1` (default) | Keep the R1 | -| `pool` | Keep both mates as independent reads | +| Value | Behavior | +|-------|----------| +| `r1` (default) | Keep the R1 read | +| `pool` | Keep both mates as separate single-end reads | | `drop` | Discard the pair | -Mates are paired by read ID. Mismatched names or unequal read counts stop the run with an error. +`merge-pairs` verifies that paired reads share matching read IDs and stops with an error if mate +names or read counts disagree. On a synthetic paired-end truth set with modeled adapter read-through, 100% of 513,715 pairs merged with 98.6% molecular count recovery. ## Non-Overlapping Pairs: Pool -Dual-anchored capture designs (Flex-Seq: R1 anchors the left probe, R2 the right) have mates -covering opposite halves of a fragment neither read spans. The mates cannot be merged, and pooling -them cannot count a window twice, because no window is covered by both mates. Concatenate both -mates into one FASTQ per sample and feed that to `normalize-reads`. +Dual-anchored capture designs (such as Flex-Seq, where R1 anchors the left probe and R2 anchors the +right probe) generate mates covering opposite ends of a larger fragment. Because the mates do not +overlap, they cannot merge, and pooling them as separate single-end reads cannot double-count a +window. Concatenate both mates into one FASTQ per sample (as used in the cranberry Flex-Seq +benchmark) and process the combined file with `normalize-reads`. If a library contains a mix of +overlapping and non-overlapping pairs, `merge-pairs --unmerged pool` merges overlapping pairs while +retaining unmerged mates as separate single-end reads. ## Multi-Window Tiling -When a fragment is longer than one window, several markers can tile one physical locus. Add a -`LocusGroup` column to the probe design to declare them as tiles: +When a target fragment spans more than one window length, multiple markers can tile the same +physical locus. Add a `LocusGroup` column to the probe-design file to declare these markers as a +tile group: ``` MarkerName TargetSequence LocusGroup @@ -51,24 +58,28 @@ amp17_snp1 ACGT...[C/T]...ACGTACGT... amp17 amp17_snp2 ACGT...C...ACG[A/G]TACGT... amp17 ``` -Tiles must share an identical Ref expansion frame (validated at load), reads locate to the group, -and then they are routed to member windows with `--group-routing`: +All tiles in a `LocusGroup` must share the same Ref expansion sequence (validated when the panel is +loaded). `normalize-reads` locates each read to the locus group and uses `--group-routing` to assign +it to member windows: -| Mode | Behaviour | Use when | -|------|-----------|----------| -| `nearest` (default) | Each read feeds exactly one tile: the fully covered window whose center is nearest the read's center | Reads are short relative to tile spacing | -| `covered` | The read is excised at every member window it fully covers | Reads span several tiles, e.g. **merged fragments** | +| Mode | Behavior | Use when | +|------|----------|----------| +| `nearest` (default) | Assigns each read to the single fully covered tile whose window center is closest to the read's center | Reads are short relative to tile spacing | +| `covered` | Excises a window for every member tile that the read fully covers | Reads span multiple tiles (e.g., merged fragments) | -Use `covered` with merged full-span fragments. They all share the amplicon's center, so with -`nearest` one tile gets almost every read: on the GT-seq benchmark one tile took effectively all -depth at 163 of 164 tiled loci. Each window still sees each fragment at most once in both modes. +Use `--group-routing covered` with merged full-span fragments. Because full-span fragments all share +the same amplicon center, `nearest` sends nearly every read to a single tile (on the GT-seq +benchmark, one tile captured almost all depth at 163 of 164 tiled loci). In both modes, each window +counts a given fragment at most once. -Fresh placement forces tiles to excise distinct sequences, since twin windows would make every -read an exact tie. Nudged members are listed in the QC as `locus_groups.window_dedup_nudged`. +During fresh window placement, `normalize-reads` ensures tiles in a group excise distinct window +sequences so reads do not tie ambiguously during assignment. The QC JSON lists adjusted tiles under +`locus_groups.window_dedup_nudged`. ## Putting It Together -The recipe validated on GT-seq: merge, normalize against a frozen panel with tile rows, generate. +The recipe validated on GT-seq is to merge, normalize against a frozen panel with tile rows, and +generate. ```bash madcats merge-pairs --fastq-dir raw/ --out-dir merged/ --jobs 8 diff --git a/docs/src/tutorials/paralog-filter.md b/docs/src/tutorials/paralog-filter.md new file mode 100644 index 0000000..33f579d --- /dev/null +++ b/docs/src/tutorials/paralog-filter.md @@ -0,0 +1,165 @@ +# Filtering Paralogs with a Reference Genome + +Some panels co-amplify paralogous copies of their target loci. When a paralogous read carries the +target base, it is assigned to the marker's RefMatch or AltMatch rows. Downstream tools that sum all +rows at the target SNP (such as `BIGr::madc2vcf_all`) then count those paralog reads as alleles of +the target locus, causing homozygous samples to appear heterozygous. This tutorial shows how to +filter an affected MADC with [`madcats filter-paralogs`](../commands/filter-paralogs.md), which +aligns haplotypes to a reference genome to identify where each sequence originates. + +> **Experimental in 0.14.0.** `filter-paralogs` is optional and currently marked experimental, so +> its options, defaults, and output formats may change in future releases. Use it on panels that +> show evidence of co-amplified paralogs. + +## Is My Panel Affected? + +Signs of co-amplified paralogs: + +- Inbred or doubled-haploid lines that should be homozygous show many heterozygous calls. +- Many markers have RefMatch/AltMatch rows that carry a large share of the marker's reads. +- Heterozygosity drops sharply when you raise `generate --min-identity` from 0.80 to 0.95 or 0.97. + Stricter identity rejects the more diverged copies at read assignment. + +The filter's QC JSON measures it in `rows.by_label.paralog.reads`, the number of +reads in rows the genome places elsewhere. In the lettuce 3K DArTag panel that was 63% of the reads +in the vendor MADC and 16% of a MADCATS MADC generated at `--min-identity 0.95`. + +## 1. Install the Aligner + +```bash +pip install 'madcats[genome]' +``` + +This adds `mappy`, minimap2's Python binding. No other command needs it. + +## 2. Index the Genome Once + +Use the design assembly of the panel, or one close to it. To compare against another +assembly, see [Using Another Assembly](../commands/filter-paralogs.md#using-another-assembly). The +first run with both `--genome` and `--genome-index` builds the index and saves it. Later runs load +it in seconds: + +```bash +madcats filter-paralogs \ + --madc project_MADC.csv \ + --genome ref/genome.fa \ + --genome-index ref/genome.sr.mmi \ + --output project_MADC_filtered.csv +``` + +On the 2.4 Gb lettuce genome indexing took 50 s and 10.6 GB of memory. Run it on a machine with +enough memory, then reuse the `.mmi` anywhere. + +## 3a. A MADCATS MADC + +Generate as usual. On a paralog-heavy panel, a stricter identity gate removes the most diverged +copies before the genome filter sees them: + +```bash +madcats generate --fastq-dir fastqs/ --reference-tags tags.csv \ + --min-identity 0.95 --jobs 8 --output project_MADC.csv + +madcats filter-paralogs \ + --madc project_MADC.csv \ + --genome-index ref/genome.sr.mmi \ + --output project_MADC_filtered.csv \ + --jobs 8 +``` + +On lettuce this pair (identity 0.95, then the genome filter dropping paralog and ambiguous rows) +matched the published realignment-based genotypes for PCA, kinship and linkage mapping. That +measurement used the bwa-mem prototype of this filter, and this command keeps the same rows for +99.7% of the reads. + +## 3b. A Vendor MADC + +The filter reads vendor DArT MADCs as delivered, with or without the starred preamble, and keeps +the preamble, the statistics columns and the column order: + +```bash +madcats filter-paralogs \ + --madc DLet22-7611_MADC.csv \ + --genome-index ref/genome.sr.mmi \ + --output DLet22-7611_MADC_filtered.csv \ + --jobs 8 +``` + +The lettuce vendor MADC (732,534 rows, 376 samples) took 2 min 15 s and 9.4 GB of memory. The filter +kept 113,667 rows, with 36% of the reads. Genotype agreement with the published realignment VCF +rose from 89.9% to 98.5%. That figure comes from the bwa-mem prototype of this filter, and this +command keeps the same rows for 99.4% of the reads. + +## 4. Read the QC + +`OUTPUT.qc.json` summarizes the filtering run. On the lettuce MADCATS MADC (17,847 rows): + +| Label | Rows | Reads | +|-------|-----:|------:| +| `on_target` | 12,687 | 59.8 M (82.4%) | +| `paralog` | 4,135 | 11.6 M (16.0%) | +| `ambiguous` | 1,025 | 1.1 M (1.6%) | + +Key metrics to inspect: + +- In `markers.placement` and `markers.clone_id_check`, the Ref tag should place nearly every + marker, and CloneID positions should generally agree. Widespread disagreements usually indicate + that the reference genome does not match the panel's design assembly, and MADCATS warns when more + than 10% of markers disagree. +- `markers.multicopy_ref_tags` lists markers whose Ref tag aligns equally well to multiple genome + sites. Although canonical rows are retained, their counts likely mix paralogous copies, so + consider excluding these markers downstream. +- `rows.by_outcome.protected` counts canonical Ref and Alt rows whose genome alignment would + otherwise have dropped them. MADCATS always retains canonical rows so downstream dosage callers + still receive both designed alleles. +- `rows.by_category` shows which allele categories lost reads. Paralogous reads typically + concentrate in RefMatch and AltMatch rows. + +## 5. Review Before Dropping (Optional) + +To inspect genome labels without removing any rows, use flag mode instead of drop mode: + +```bash +madcats filter-paralogs --madc project_MADC.csv --genome-index ref/genome.sr.mmi \ + --paralogs flag --ambiguous flag --output project_MADC_flagged.csv +``` + +In flag mode, each row records its label in the `GenomeLabel` column (replacing the `PICRef` +position). The `OUTPUT.genome_labels.csv` sidecar reports each row's alignment score at its marker +site alongside its best score elsewhere in the genome. A perfect 81 bp match scores 162, and each +mismatch subtracts 10 points. For example, a row with `TargetScore` 132 and `OffTargetScore` 162 +differs from the target site by three mismatches while matching an off-target locus exactly. + +Passing `--ambiguous keep` retains ambiguous rows without adding a label column. By default, +ambiguous rows are dropped because keeping them increased false heterozygous calls in inbred lettuce +lines (see [Options](../commands/filter-paralogs.md#options)). + +## 6. Continue Downstream + +The filtered MADC preserves the input file's layout. A filtered raw MADC proceeds through the +standard downstream workflow: HapApp or HapApp_utils for fixed allele IDs, followed by +`BIGr::madc2vcf_all()` and dosage calling (see +[Output Formats](../reference/output-formats.md#downstream-processing)). + +`filter-paralogs` also accepts HapApp's fixed-allele-ID output, so you can run it after HapApp +instead: + +```bash +madcats filter-paralogs \ + --madc project_MADC_rename_v1.csv \ + --genome-index ref/genome.sr.mmi \ + --output project_MADC_rename_v1_filtered.csv +``` + +The command preserves fixed allele IDs and column layout, so the filtered file remains directly +compatible with downstream tools. On the lettuce MADCATS MADC rewritten in HapApp's layout, every +row received the exact same genome label as in the raw MADC. + +## How the Labels Are Decided + +`filter-paralogs` first locates each marker on the reference genome using its Ref tag and CloneID +position, then aligns every distinct haplotype both genome-wide and locally at the marker site. It +compares the two best alignment scores: a higher score at the marker site yields `on_target`, a +higher score elsewhere yields `paralog`, and an equal score yields `ambiguous`. See the +[command page](../commands/filter-paralogs.md#description) for algorithm details and +[Validation & Accuracy](../reference/validation.md#genome-paralog-filter-filter-paralogs) for +comparisons against bwa-mem and blastn. diff --git a/docs/src/tutorials/primer-free.md b/docs/src/tutorials/primer-free.md index 8dd9845..bc19e78 100644 --- a/docs/src/tutorials/primer-free.md +++ b/docs/src/tutorials/primer-free.md @@ -1,7 +1,7 @@ # Panels Without a Primer File Some providers do not share the primer file. The only thing MADCATS needs from it is where each tag -starts inside the probe-design target, and that can be recovered from the reads. +starts inside the probe-design target, and MADCATS can recover that from the reads. ## Option A: Bootstrap From a Delivered MADC @@ -14,9 +14,10 @@ python3 scripts/madc_to_reference_tags.py \ --output reference_tags.csv ``` -Markers that cannot become loci are announced with a `WARNING:` and listed with their reason in -`reference_tags.csv.skipped.tsv`. The most common reason is Ref and Alt rows carrying the same -sequence, which means the variant lies one base past the window or the design is presence/absence. +The script announces markers that cannot become loci with a `WARNING:` and lists them with their +reason in `reference_tags.csv.skipped.tsv`. The most common reason is Ref and Alt rows carrying the +same sequence, which means the variant lies one base past the window or the design is +presence/absence. Prefer this route when a vendor MADC is available. It reproduces the vendor's tags, including IUPAC curation. @@ -36,31 +37,33 @@ madcats infer-design \ ### How it works The tag must be a tag-length window of the bracket-expanded target that contains the variant. So -inference only has to choose among a fixed set of candidate windows (about 4x tag length per locus); -it never assembles new sequences. Because reads are primer-started, exact read prefixes almost -always point clearly to one window. Ref/Alt identity comes from bracket order. +inference only has to choose among a fixed set of candidate windows (about 4x tag length per locus) +and never assembles new sequences. Because reads are primer-started, exact read prefixes almost +always point to only one window. Ref/Alt identity comes from bracket order. -Votes are counted in two tiers, in order: +Inference counts votes in two tiers, in order: 1. The exact tier counts reads whose prefix exactly matches a candidate window. When a locus has any exact votes, they decide. 2. The fuzzy tier runs only for loci with no exact votes. It accepts reads that pass the same 80% identity rule as `generate`. -A winning window needs at least `--dominance-ratio` (default 10) times the runner-up's votes. The -`LeftPrimerSequence` written to the CSV is the shortest tag prefix that is unique in the panel, -which may be shorter or longer than the real primer. The reads do not show where the real primer -ends, and assignment does not need it. +A winning window must have at least `--dominance-ratio` (default 10) times as many votes as the +runner-up. The `LeftPrimerSequence` written to the CSV is the shortest tag prefix that uniquely +identifies the locus across the panel, which may be shorter or longer than the physical primer. The +reads alone do not reveal where the physical primer ends, and read assignment does not require that +boundary. ### Check the result -The `inferred_reference_tags.csv.qc.json` report records each locus's route, support, margin, -anchor length and flags, plus the loci excluded and why. +The `inferred_reference_tags.csv.qc.json` report records each locus's inference route, vote +support, dominance margin, anchor length, and flags, along with any excluded loci and why they were +omitted. -Review the fuzzy-tier loci. When the fuzzy tier picks the wrong window, it is usually because a -paralog supplied the reads, and the wrong window then wins by a large margin, so the QC statistics -cannot flag it. Cross-check `fuzzy_anchor` loci against any delivered MADC's -canonical rows or a public panel resource. +Review loci inferred through the fuzzy tier carefully. When the fuzzy tier selects the wrong window, +a co-amplified paralog is usually the source of the reads, and the wrong window can win by a large +margin that QC metrics alone cannot flag. Cross-check `fuzzy_anchor` loci against a delivered MADC's +canonical rows or a public panel resource whenever possible. If you have a ground-truth panel for comparison: @@ -80,19 +83,19 @@ madcats generate \ --output project_MADC.csv ``` -Inference is a one-time operation per panel: freeze the CSV and reuse it for every later order. +Inference is a one-time operation per panel, so freeze the CSV and reuse it for every later order. ## How Accurate Is Inference? | Project | Result | |---------|--------| -| Sweetpotato DArTag (blinded) | 3,068/3,120 loci inferred: exact tier 100.0% correct (2,742), fuzzy tier 97.9% (319/326); zero Ref/Alt swaps. `generate` on the inferred panel reproduced 99.1% of rows with 100% classification agreement. | +| Sweetpotato DArTag (blinded) | 3,068/3,120 loci inferred, with the exact tier 100.0% correct (2,742), the fuzzy tier 97.9% (319/326) and zero Ref/Alt swaps. `generate` on the inferred panel reproduced 99.1% of rows with 100% classification agreement. | | Delta smelt GT-seq | 368/368 loci exactly as the physical primers define them | | Alfalfa DArTag (raw reads) | 2,999/3,000 loci in the exact tier, all identical to the design tags | -| Blackberry DArTag | 2,943/3,015 inferred; 18 wrong windows (0.6%), all at read-starved or short-amplicon loci | +| Blackberry DArTag | 2,943/3,015 inferred, with 18 wrong windows (0.6%), all at read-starved or short-amplicon loci | ## Raw Deliveries and Tag Length `infer-design` takes the same `--leading-anchor` option as `generate` for raw DArT deliveries. `--tag-length` sets the panel's reported tag length (54, 81, 109, ...). Reads must reach it, and the -design flanks must contain a full window; both are validated per locus. +design flanks must contain a full window. MADCATS validates both per locus. diff --git a/madcats.py b/madcats.py index 532075c..4f31cca 100644 --- a/madcats.py +++ b/madcats.py @@ -7,9 +7,13 @@ FASTQ-to-MADC workflow, where MADC denotes the Missing Allele Discovery Counts format. -The implementation intentionally uses only the Python standard library. +The implementation intentionally uses only the Python standard library. The +one exception is optional: ``filter-paralogs``, in its own module +``madcats_paralogs.py``, imports the ``mappy`` aligner on first use +(``pip install madcats[genome]``). -Seven subcommands cover the read models the pipeline understands: +Seven subcommands cover the read models the pipeline understands, and an eighth +cleans a finished table: - ``design`` reconstructs each marker's canonical Ref/Alt tags from vendor primer + probe-design files. This is the primer-started, single-end model @@ -47,6 +51,14 @@ panel routes above into the MADC table, via the stages listed below. - ``validate`` compares a generated MADC against a reference MADC row-by-row and cell-by-cell, reporting precision/recall by allele category. +- ``filter-paralogs`` (optional; needs ``mappy``; in ``madcats_paralogs.py``) + cleans a MADC from ``generate``, a vendor delivery or HapApp with a + reference genome. Each marker is placed by aligning its Ref tag, every + haplotype is aligned, and rows whose best genome hit lies at another locus + (paralogs) or ties between loci (ambiguous) are dropped or flagged. It is + meant for panels where co-amplified paralogous copies inflate + heterozygosity when counts are summed per SNP; canonical rows are never + dropped. Pipeline stages (the ``generate`` command; see ``run_generate``): @@ -60,7 +72,10 @@ length tag, and accept it within the substitution-only identity envelope of the locus's Ref/Alt tags — or, when every candidate rejects it, under one gapped reading within the same edit budget, so undesigned indel - haplotypes are counted rather than dropped (``select_marker``). Tags + haplotypes are counted rather than dropped (``select_markers``). Tiles + are the one exception to one read per locus: they read the same tag + window of one amplicon (``tile_families``), so a read that fits several + tiles is credited to each, and the extra credits are counted apart. Tags carrying an N are credited to the one N-free sequence they fit or dropped; they never become rows. Counting exact observed sequences — never consensus-corrected ones — is what makes the output auditable @@ -89,6 +104,9 @@ Ref and Alt rows — even at zero reads — because downstream dosage tools need the biallelic axis present unconditionally. Novel rows must pass the evidence rule; excluded reads are tallied, never silently dropped. + ``--remove-primers on`` acts here and nowhere earlier: the rows are + chosen and classified on the full tags, then written without their + primers, and rows that become identical are added together. 7. QC/provenance. A JSON sidecar records inputs, parameters, panel fingerprints, per-sample QC, and a full read-accounting ledger from raw records through emitted rows, so any run can be audited and reproduced. @@ -100,19 +118,23 @@ 1. Sequence and file utilities (IUPAC matching, mismatch counts, CSV/FASTQ helpers). 2. Alignment engine: the Myers prescreen, the banded DP, and - ``accepted_gapped_reading``/``row_reading`` — the one gapped reading a - row may be given. + ``accepted_gapped_reading``/``row_decision`` — the one gapped reading a + row may be given, where a row stops being read because its end has + two explanations, and how the bases after the tag settle such an end. 3. Panel definition: design-file reconstruction, reference-tag tables, and primer-free inference. 4. Platform intake: pair merging, window location and freezing, tiling and routing, window-scan. -5. Per-sample read assignment: ``PrimerIndex``, ``select_marker``, - ``process_sample`` and its cache. +5. Per-sample read assignment: ``PrimerIndex``, ``tile_families``, + ``select_markers``, ``process_sample`` and its cache; the bases after + a tag (``keeps_continuation``, ``pooled_continuations``). 6. Evidence, denoising and partial-read salvage: ``EvidenceRule``, ``collect_evidence``, ``finalize_counts``, ``apply_partial_reads``. 7. Classification and annotation: ``classify_sequence``, ``variant_events``, - ``marker_type_label``. + ``marker_type_label``; then primer removal (``--remove-primers``): + ``amplicon_geometry``, ``right_primer_cut``, ``trim_locus_rows``. 8. MADC input/output and QC: ``read_madc``, ``write_madc``, ``validate_madc``. + The genome paralog filter is in ``madcats_paralogs.py``. 9. Commands and command line: one ``run_*`` per subcommand, ``build_parser``. Vocabulary. *tag*: the fixed-length sequence a read is measured as (intake @@ -144,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, +) # ============================================================================ @@ -152,14 +176,14 @@ # ============================================================================ -__version__ = "0.13.0" +__version__ = "0.14.0" # Increment only when the serialized per-sample cache or raw-read processing # changes. Output-row filtering does not invalidate reusable FASTQ counts. # 0.4.0: fuzzy primer matches resolve across all matched depths by tag # identity instead of preferring the deepest primer, so caches built with # --primer-mismatches 1 (or prefix-nested panels) must be regenerated. -CACHE_FORMAT_VERSION = "0.5.0" +CACHE_FORMAT_VERSION = "0.8.0" TAG_LENGTH_DEFAULT = 81 QUALITY_THRESHOLDS = (10, 20, 30, 40) @@ -213,10 +237,19 @@ GAP_MAX_SUBSTITUTIONS = 6 # composition guard: an indel haplotype is its canonical plus gaps and FEW substitutions GAP_MAX_EVENTS = 6 # ... in few separate gap events; a co-amplified paralog needs many substitutions GAP_VERIFIED_SUFFIX = 12 # bases that must follow the last gap before a gapped reading may re-read the target +CONTINUATION_BASES = 40 # read continuation: bases after the tag kept from a read +CONTINUATIONS_KEPT = 3 # ... commonest continuations kept per tag and sample, each at every length it arrives in +CONTINUATION_REACHED_BY = 0.9 # ... a tag's are cut to the longest length this share of its reads reach +CONTINUATION_MIN_READS = 3 # ... a tag's commonest continuation counts with this many reads (kept once a sample has as many of the tag) +CONTINUATION_MIN_SHARE = 0.6 # ... and this share of the tag's reads that reach that length +CONTINUATION_MAX_MISMATCHES = 2 # ... a longer window settles a row only if it reads the added bases this cleanly PARTIAL_TAIL_DEFAULT = 9 # --min-partial-length defaults to --tag-length minus this: at most 9 unobserved tail bases LEADING_ANCHOR_SEARCH = 40 # --leading-anchor: the anchor must end within this many bases beyond its own length +LEADING_ANCHOR_MISMATCHES_DEFAULT = 0 # --leading-anchor-mismatches: substitutions tolerated in the anchor +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): @@ -237,8 +270,9 @@ class Locus: # Markers sharing a locus_group are windows (tiles) of one physical # locus: normalize-reads locates reads to the group and routes them # among the member windows (--group-routing: one tile per read, or - # every fully covered tile). Empty = the marker is its own group - # (the universal pre-0.9 case). + # every fully covered tile), and generate credits a read to every + # member that reads the same tag window (tile_families). Empty = the + # marker is its own group (the universal pre-0.9 case). locus_group: str = "" @property @@ -263,6 +297,11 @@ class SampleResult: partial_quality_support: Dict[Tuple[int, str], Tuple[int, ...]] qc: Dict[str, int] cache_hit: bool = False + # (marker index, tag) -> [(bases after the tag, reads)], commonest first (keeps_continuation) + continuations: Dict[Tuple[int, str], List[Tuple[str, int]]] = dataclasses.field(default_factory=dict) + # Reads outside the top CONTINUATIONS_KEPT prefix-collapsed families: + # (marker index, tag) -> [(shared_prefix_with_kept_or_empty, read_length, reads)] + continuation_residuals: Dict[Tuple[int, str], List[Tuple[str, int, int]]] = dataclasses.field(default_factory=dict) class EvidenceSupport(NamedTuple): @@ -281,6 +320,7 @@ class GappedReading(NamedTuple): counts describe it; ``last_gap_end`` is the read index just after the last gap; ``ref_to_read`` maps aligned reference indices to read indices (reference bases inside a deletion, or past the aligned end, are absent). + ``template`` is the canonical tag the reading was made against. """ edits: int @@ -292,6 +332,20 @@ class GappedReading(NamedTuple): end_ref: int last_gap_end: int ref_to_read: Dict[int, int] + template: str = "" + + +class RowDecision(NamedTuple): + """How a row is read against its marker (row_decision). + + ``reading`` is the accepted gapped reading, or None when the row is read + at the fixed offsets. ``unresolved`` is None when the whole row is + read, or ``(ref_index, row_index)``: the Ref-tag position and the base + of the row from which, to their ends, the row is not read at all. + """ + + reading: Optional[GappedReading] + unresolved: Optional[Tuple[int, int]] @dataclasses.dataclass(frozen=True) @@ -309,9 +363,11 @@ class AssignmentSettings: partial_min_length: int gap_band: int # --max-indel-length, or 0 with --gapped-rescue off leading_anchor: str = "" # --leading-anchor: constant sequence preceding the amplicon in raw deliveries + tile_families: Tuple[Tuple[int, ...], ...] = () # --tile-groups: marker indices credited together (tile_families) + leading_anchor_mismatches: int = 0 # --leading-anchor-mismatches: substitutions tolerated when no exact anchor is found def cache_arguments(self) -> Dict[str, object]: - return { + arguments: Dict[str, object] = { "tag_length": self.tag_length, "max_offtarget_mismatches": self.max_offtarget_mismatches, "gap_band": self.gap_band, @@ -320,6 +376,21 @@ def cache_arguments(self) -> Dict[str, object]: "leading_anchor": self.leading_anchor, "quality_thresholds": QUALITY_THRESHOLDS, } + # Keyed only when present: a panel without tiles is read exactly as + # before tile crediting existed, so its caches stay valid, while any + # tile family (and any change to the families) gives a new fingerprint. + if self.tile_families: + arguments["tile_families"] = [list(family) for family in self.tile_families] + # Likewise keyed only when it changes the read pass: exact-anchor and + # anchor-free runs keep the fingerprints (and caches) they had before, + # and so do anchors too short to be matched with a substitution. + if ( + self.leading_anchor + and self.leading_anchor_mismatches + and len(self.leading_anchor) >= LEADING_ANCHOR_MISMATCH_MIN_LENGTH + ): + arguments["leading_anchor_mismatches"] = self.leading_anchor_mismatches + return arguments @dataclasses.dataclass(frozen=True) @@ -333,12 +404,13 @@ class DenoiseSettings: @dataclasses.dataclass(frozen=True) class OutputOptions: - """How ``write_madc`` lays the table out; nothing here changes a count.""" + """How ``write_madc`` lays the table out; nothing here adds or removes a read.""" number_match_ids: bool = False preamble: Optional[Sequence[Sequence[str]]] = None annotations: bool = True variants_path: Optional[Path] = None + remove_primers: bool = False # rows that become identical are then one row with their reads added # ============================================================================ @@ -500,6 +572,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``. @@ -517,32 +599,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) @@ -559,18 +635,24 @@ 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):])) + # 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): @@ -647,7 +729,7 @@ def gapped_stats(read: str, ref: str, band: int): @functools.lru_cache(maxsize=4096) -def gapped_alignment(read: str, ref: str, band: int): +def gapped_alignment(read: str, ref: str, band: int, whole: bool = False): """The alignment the annotations describe: ``(ops, end_read, end_ref, edits)``. Same start-anchored, end-free band and the same minimum edit count as @@ -662,10 +744,13 @@ def gapped_alignment(read: str, ref: str, band: int): deleted before read index ``i``). ``end_read`` and ``end_ref`` are the aligned lengths: read bases from ``end_read`` on overhang the reference (a deletion pulled downstream sequence into the window) and reference - bases from ``end_ref`` on were pushed out of it by an insertion. Cached - because a row is described more than once per run. + bases from ``end_ref`` on were pushed out of it by an insertion. With + ``whole`` both sequences are aligned to their last base instead (two + sequences of different lengths that end at the same place, such as rows + cut at their right primer); their lengths may differ by at most ``band``. + Cached because a row is described more than once per run. """ - return _three_state_alignment(read, ref, band, open_penalty=1, sub_penalty=0) + return _three_state_alignment(read, ref, band, open_penalty=1, sub_penalty=0, whole=whole) @functools.lru_cache(maxsize=4096) @@ -683,9 +768,10 @@ def fewest_substitution_alignment(read: str, ref: str, band: int): return _three_state_alignment(read, ref, band, open_penalty=0, sub_penalty=1) -def _three_state_alignment(read: str, ref: str, band: int, open_penalty: int, sub_penalty: int): +def _three_state_alignment(read: str, ref: str, band: int, open_penalty: int, sub_penalty: int, whole: bool = False): """Start-anchored, end-free banded alignment minimising ``edits * GAP_OPEN_SCALE`` - plus ``open_penalty`` per gap opening and ``sub_penalty`` per substitution.""" + plus ``open_penalty`` per gap opening and ``sub_penalty`` per substitution. + ``whole`` anchors the end as well: both sequences are used to their last base.""" n, m = len(read), len(ref) INF = 1 << 60 scale = GAP_OPEN_SCALE @@ -709,8 +795,9 @@ def _three_state_alignment(read: str, ref: str, band: int, open_penalty: int, su match_row[j] = diagonal + (sub_cost if base not in ref_sets[j - 1] else 0) insert_row[j] = min(match_up[j] + scale + open_penalty, insert_up[j] + scale, delete_up[j] + scale + open_penalty) delete_row[j] = min(match_row[j - 1] + scale + open_penalty, insert_row[j - 1] + scale + open_penalty, delete_row[j - 1] + scale) - ends = [(min(match_table[n][j], insert_table[n][j], delete_table[n][j]), n, j) for j in range(max(0, m - band), m + 1)] - ends += [(min(match_table[i][m], insert_table[i][m], delete_table[i][m]), i, m) for i in range(max(0, n - band), n + 1)] + ends = [(min(match_table[n][j], insert_table[n][j], delete_table[n][j]), n, j) for j in range(m if whole else max(0, m - band), m + 1)] + if not whole: + ends += [(min(match_table[i][m], insert_table[i][m], delete_table[i][m]), i, m) for i in range(max(0, n - band), n + 1)] cost, i, j = min(ends) end_read, end_ref = i, j state = min((match_table[i][j], 0), (insert_table[i][j], 1), (delete_table[i][j], 2))[1] @@ -746,15 +833,32 @@ def accepted_gapped_reading( substitution-only reading (``substitutions``, the caller's bound; by default the mismatch count against ``template``), well composed (``gapped_explanation_ok``) and verified by at least GAP_VERIFIED_SUFFIX - bases after its last gap. A reading that fails any test is not a - reading of the row at all: the row is then classified at the fixed - offset and described as substitutions, by both consumers alike. + bases after its last gap. A reading that is no cheaper or badly + composed is not a reading of the row at all: the row is then classified + at the fixed offset and described as substitutions, by both consumers + alike. One that only lacks the verifying bases is not taken either, + but it leaves the row's end unresolved (row_decision). """ + reading = _unverified_gapped_reading(sequence, template, gap_band, substitutions) + return reading if reading is not None and _gap_verified(reading, sequence) else None + + +def _gap_verified(reading: GappedReading, sequence: str) -> bool: + """At least GAP_VERIFIED_SUFFIX bases of the row follow the reading's last gap.""" + return reading.last_gap_end <= len(sequence) - GAP_VERIFIED_SUFFIX + + +def _unverified_gapped_reading( + sequence: str, template: str, gap_band: int, substitutions: Optional[int] = None +) -> Optional[GappedReading]: + """accepted_gapped_reading before its last test: the fewest-openings + alignment when it is strictly cheaper than substitutions and well + composed, whether or not enough bases follow its last gap to verify it.""" if gap_band <= 0 or len(template) != len(sequence): 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: @@ -774,10 +878,7 @@ def accepted_gapped_reading( previous = kind if not gapped_explanation_ok(guard_subs, guard_bases, guard_events): return None - reading = _reading_from_ops(sequence, template, ops, end_read, end_ref, edits) - if reading.last_gap_end > len(sequence) - GAP_VERIFIED_SUFFIX: - return None - return reading + return _reading_from_ops(sequence, template, ops, end_read, end_ref, edits) def _reading_from_ops(sequence: str, template: str, ops, end_read: int, end_ref: int, edits: int) -> GappedReading: @@ -795,25 +896,317 @@ def _reading_from_ops(sequence: str, template: str, ops, end_read: int, end_ref: gap_events += previous != kind last_gap_end = max(last_gap_end, i + 1 if kind == "I" else i) previous = kind - return GappedReading(edits, substitutions, gap_bases, gap_events, ops, end_read, end_ref, last_gap_end, ref_to_read) + return GappedReading(edits, substitutions, gap_bases, gap_events, ops, end_read, end_ref, last_gap_end, ref_to_read, template) + + +def _reading_cost(reading: GappedReading) -> Tuple[int, int]: + """How the two canonicals' readings of one row are ranked: fewest edits, + then fewest gap openings. + A row can fit the Ref tag and the Alt tag in the same number of edits: + six inserted bases as one insertion beside the Alt base, or split in two + around a Ref base. The reading with fewer separate gaps is the one + taken, as gapped_alignment already takes it among the alignments to one + tag. Readings equal in both leave the Ref tag's standing (it is tried + first).""" + return reading.edits, reading.gap_events -def row_reading(locus: Locus, sequence: str, gap_band: int) -> Optional[GappedReading]: + +def row_reading( + locus: Locus, sequence: str, gap_band: int, continuations: Optional[Mapping[str, str]] = None +) -> Optional[GappedReading]: """The locus-level decision both consumers share: the accepted gapped reading - of ``sequence`` against whichever canonical explains it most cheaply, or - ``None``. The bound a gapped reading must beat is the cheaper of the two + of ``sequence`` against whichever canonical explains it most cheaply + (_reading_cost), or ``None``. The bound a gapped reading must beat is the cheaper of the two substitution-only readings, and the composition guard is applied against the canonical the row is read from, so a designed substitution never counts against an AltMatch row's indel reading.""" - if gap_band <= 0: + return row_decision(locus, sequence, gap_band, continuations).reading + + +def row_decision( + locus: Locus, sequence: str, gap_band: int, continuations: Optional[Mapping[str, str]] = None +) -> RowDecision: + """How a row is read: its accepted gapped reading, and where it stops being read. + + Over both canonicals there is the cheapest gapped reading that is + verified (row_reading: GAP_VERIFIED_SUFFIX bases follow its last gap) + and the cheapest one whether verified or not. Cheapest is fewest + edits, then fewest gap openings (_reading_cost). Where the two are the + same reading, or no gapped reading is cheaper than substitutions, the + whole row is read. Where they differ, the row's end has two + explanations and too few bases to tell them apart: a gap there, or the + reading without it. The row is then read up to the first Ref-tag + position at which the two explanations show a different base of the + row, and from there on it is unresolved. Neither explanation is taken + for that stretch: a target in it classifies as Other, and the row's + Variants close with ``unresolved`` in place of substitutions or a gap. + + A gap earlier in the row is kept when GAP_VERIFIED_SUFFIX bases after + it read with at most CONTINUATION_MAX_MISMATCHES mismatches + (_verified_prefix_reading). The row is then unresolved only from the + later gap on, and a target before that gap is read through the kept one. + + The first such position is found with each gap at the rightmost of its + equal placements (_right_align), so every base both explanations agree + on stays read. The decision is made once here and shared by + classify_sequence, variant_events and the primer removal. + + ``continuations`` maps a tag of this marker to the bases its reads + carry after it (pooled_continuations). With them, a row whose target + lies in an unresolved end is decided again on a longer window + (_continued_decision). That is asked before an earlier gap is kept, so + a row the longer window settles is read whole. A row whose target the + tag reads without either step is never asked, so its category cannot + change. + """ + if gap_band <= 0 or sequence in (locus.ref_tag, locus.alt_tag): + return RowDecision(None, None) + if continuations: + plain = _row_decision(locus.ref_tag, locus.alt_tag, sequence, gap_band, GAP_VERIFIED_SUFFIX, False) + if _target_unread(locus, plain): + settled = _continued_decision(locus, sequence, gap_band, continuations) + if settled is not None: + return settled + return _row_decision(locus.ref_tag, locus.alt_tag, sequence, gap_band, GAP_VERIFIED_SUFFIX) + + +def _target_unread(locus: Locus, decision: RowDecision) -> bool: + """The marker's target lies in the end the decision leaves unresolved.""" + return decision.unresolved is not None and locus.variant_pos >= decision.unresolved[0] + + +def _continued_decision( + locus: Locus, sequence: str, gap_band: int, continuations: Mapping[str, str] +) -> Optional[RowDecision]: + """The decision of a row whose target is unread, made on a longer window; None when that settles nothing. + + The window is the row and the two canonical tags, each followed by the + bases its own reads carry after the tag (the Alt tag borrows the Ref + tag's when it has none). It is the same decision on more bases + (_row_decision), with no new way to align. Its answer is taken when + the window grows by at least GAP_VERIFIED_SUFFIX bases, its own end is + resolved, and it reads the added bases with at most + CONTINUATION_MAX_MISMATCHES substitutions. The last test keeps out a + row that only fits the longer tags through many substitutions. + + The answer is cut back to the tag (_cut_reading): the row is read as + far as its own bases go. A target the longer window finds past the tag + is not in the row, and the row stays Other. + """ + row_more = continuations.get(sequence) + ref_more = continuations.get(locus.ref_tag) + if not row_more or not ref_more: return None - substitutions = min(tag_mismatches(sequence, locus.ref_tag), tag_mismatches(sequence, locus.alt_tag)) - best: Optional[GappedReading] = None - for template in (locus.ref_tag, locus.alt_tag): - accepted = accepted_gapped_reading(sequence, template, gap_band, substitutions) - if accepted is not None and (best is None or accepted.edits < best.edits): - best = accepted - return best + alt_more = continuations.get(locus.alt_tag) or ref_more + added = min(len(row_more), len(ref_more), len(alt_more)) + if added < GAP_VERIFIED_SUFFIX: + return None + row = sequence + row_more[:added] + ref = locus.ref_tag + ref_more[:added] + alt = locus.alt_tag + alt_more[:added] + reading, unresolved = _row_decision(ref, alt, row, gap_band, GAP_VERIFIED_SUFFIX, False) + if unresolved is not None: + return None + length = len(sequence) + if reading is None: + mismatches = min(tag_mismatches(row[length:], template[length:]) for template in (ref, alt)) + else: + mismatches = sum( + 1 for kind, i, j in reading.ops + if kind == "M" and i >= length and not _design_matches(row[i], reading.template[j]) + ) + if mismatches > CONTINUATION_MAX_MISMATCHES: + return None + return RowDecision(None if reading is None else _cut_reading(reading, sequence), None) + + +def _cut_reading(reading: GappedReading, sequence: str) -> GappedReading: + """A longer window's reading as the row itself shows it. + + Kept are the alignment steps that use the row's own bases and the tag's + own positions. The reading ends where an insertion pushes the tag's + bases past the row, or a deletion pulls in bases from past the tag, as + it does for a row read on its tag alone (gapped_alignment).""" + length = len(sequence) + template = reading.template[:length] + ops, end_read, end_ref = _cut_alignment(reading.ops, 0, length, length) + edits = sum(1 for kind, i, j in ops if kind != "M" or not _design_matches(sequence[i], template[j])) + return _reading_from_ops(sequence, template, ops, end_read, end_ref, edits) + + +def _cut_alignment(ops, start: int, row_length: int, ref_length: int): + """The steps of an alignment among ``row_length`` row bases and ``ref_length`` template bases from + ``start`` on, counted from there: ``(ops, end_read, end_ref)`` as gapped_alignment gives them.""" + kept = tuple( + (kind, i - start, j - start) + for kind, i, j in ops + if start <= i < start + row_length and start <= j < start + ref_length + ) + end_read = sum(1 for kind, _, _ in kept if kind != "D") + end_ref = sum(1 for kind, _, _ in kept if kind != "I") + return kept, end_read, end_ref + + +def _verified_prefix_reading( + sequence: str, reading: GappedReading, verified_suffix: int +) -> Optional[GappedReading]: + """The verified early gaps of an unverified reading, kept when a later gap lacks verifying bases. + + Walks gap runs from the end of ``reading.ops``: any run whose end lies + within ``verified_suffix`` bases of the end — or of the next unverified gap + run — is dropped, and the reading continues base-by-base from there. + Returns ``None`` when no verified gap remains, or when the remaining prefix + is not strictly cheaper than substitutions.""" + ops = reading.ops + runs = [] + k = 0 + while k < len(ops): + kind = ops[k][0] + if kind == "M": + k += 1 + continue + end = k + while end + 1 < len(ops) and ops[end + 1][0] == kind: + end += 1 + read_start = ops[k][1] + read_end = ops[end][1] + 1 if kind == "I" else ops[end][1] + runs.append((k, read_start, read_end)) + k = end + 1 + boundary = len(sequence) + cut_op: Optional[int] = None + verified_runs = 0 + for start_op, read_start, read_end in reversed(runs): + if read_end > boundary - verified_suffix: + boundary = read_start + cut_op = start_op + else: + verified_runs += 1 + if cut_op is None or verified_runs == 0: + return None + template = reading.template + # Each kept gap must be followed by bases that read cleanly: a wrong alignment (an adapter, + # another locus, a deletion past the band) has gaps among substitutions. The first gap that + # fails is where the reading stops; clean gaps before it are kept. + while True: + kept_runs, failed = 0, None + for start_op, read_start, read_end in runs: + if start_op >= cut_op: + break + run_end = start_op + while run_end + 1 < len(ops) and ops[run_end + 1][0] == ops[start_op][0]: + run_end += 1 + after = [(i, j) for kind, i, j in ops[run_end + 1 : cut_op] if kind == "M"][:verified_suffix] + if len(after) < verified_suffix or sum( + not _design_matches(sequence[i], template[j]) for i, j in after + ) > CONTINUATION_MAX_MISMATCHES: + failed = start_op + break + kept_runs += 1 + if failed is None: + break + cut_op = failed + if kept_runs == 0: + return None + prefix_ops = ops[:cut_op] + cur_i = prefix_ops[-1][1] + 1 if prefix_ops else 0 + cur_j = prefix_ops[-1][2] + 1 if prefix_ops else 0 + prefix_edits = sum( + 1 for kind, i, j in prefix_ops if kind != "M" or not _design_matches(sequence[i], template[j]) + ) + shared = min(cur_i, cur_j) + if prefix_edits >= tag_mismatches(sequence[:shared], template[:shared]): + return None + tail_len = min(len(sequence) - cur_i, len(template) - cur_j) + full_ops = prefix_ops + tuple(("M", cur_i + step, cur_j + step) for step in range(tail_len)) + end_read, end_ref = cur_i + tail_len, cur_j + tail_len + edits = sum(1 for kind, i, j in full_ops if kind != "M" or not _design_matches(sequence[i], template[j])) + return _reading_from_ops(sequence, template, full_ops, end_read, end_ref, edits) + + +@functools.lru_cache(maxsize=65536) +def _row_decision( + ref_tag: str, alt_tag: str, sequence: str, gap_band: int, verified_suffix: int, keep_prefix: bool = True +) -> RowDecision: + """row_decision, cached per row (classification and annotation both ask).""" + substitutions = min(tag_mismatches(sequence, ref_tag), tag_mismatches(sequence, alt_tag)) + verified = cheapest = None + verified_template = cheapest_template = "" + for template in (ref_tag, alt_tag): + reading = _unverified_gapped_reading(sequence, template, gap_band, substitutions) + if reading is None: + continue + cost = _reading_cost(reading) + if cheapest is None or cost < _reading_cost(cheapest): + cheapest, cheapest_template = reading, template + if reading.last_gap_end <= len(sequence) - verified_suffix and (verified is None or cost < _reading_cost(verified)): + verified, verified_template = reading, template + if cheapest is None or (verified is not None and verified.ops == cheapest.ops and verified_template == cheapest_template): + return RowDecision(verified, None) + # Keep verified early gaps when an unverified late gap prevented the whole + # alignment from passing the suffix check; also avoid comparing Ref-tag and + # Alt-tag positions across a designed indel where their coordinates differ. + cross_frame = ( + verified is not None + and verified_template != cheapest_template + and any(kind in ("ins", "del") for kind, *_ in _designed_events(ref_tag, alt_tag, gap_band)) + ) + if keep_prefix and (verified is None or cross_frame): + prefix = _verified_prefix_reading(sequence, cheapest, verified_suffix) + verified = prefix + verified_template = cheapest_template if prefix is not None else "" + # Two explanations of the row's end. Which base of the row stands at each + # Ref-tag position under each, gaps at their rightmost placement: + shown = {j: i for kind, i, j in _right_align(cheapest.ops, sequence, cheapest_template) if kind == "M"} + kept_ops = None if verified is None else _right_align(verified.ops, sequence, verified_template) + kept = None if kept_ops is None else {j: i for kind, i, j in kept_ops if kind == "M"} + first = next( + (j for j in range(len(sequence)) if (j if kept is None else kept.get(j)) != shown.get(j)), None + ) + if first is None: + return RowDecision(verified, None) + # The row bases the agreed part uses: an insertion placed right before the + # first disputed position belongs to the dispute. + start = first if kept_ops is None else sum(1 for kind, _, j in kept_ops if kind != "D" and j < first) + return RowDecision(verified, (first, start)) + + +def _right_align(ops, read: str, ref: str): + """Shift every gap run right across matching bases: the mirror of _left_align. + + Of the equal placements of a gap inside a repeat this is the one that + agrees with the reading without the gap for the longest, so it marks + where two readings of a row really part ways.""" + ops = list(ops) + k = len(ops) - 1 + while k >= 0: + kind = ops[k][0] + if kind == "M": + k -= 1 + continue + a = k + while a - 1 >= 0 and ops[a - 1][0] == kind: + a -= 1 + b = k + start = a + while b + 1 < len(ops) and ops[b + 1][0] == "M": + _, next_i, next_j = ops[b + 1] + if read[next_i] != ref[next_j]: + break + if kind == "I": + first_i = ops[a][1] + if read[next_i] != read[first_i]: + break + ops[a : b + 2] = [("M", first_i, next_j)] + [("I", ops[t][1] + 1, next_j + 1) for t in range(a, b + 1)] + else: + first_j = ops[a][2] + if ref[next_j] != ref[first_j]: + break + ops[a : b + 2] = [("M", next_i, first_j)] + [("D", next_i + 1, ops[t][2] + 1) for t in range(a, b + 1)] + a += 1 + b += 1 + k = start - 1 + return ops def _left_align(ops, read: str, ref: str): @@ -1062,6 +1455,7 @@ def build_panel(primer_csv: Path, probe_design: Path, tag_length: int) -> List[L variant_pos=variant_pos, ref_tag=ref_tag, alt_tag=alt_tag, + locus_group=(designs[marker].get("LocusGroup") or "").strip(), ) ) return loci @@ -1316,7 +1710,6 @@ def _infer_fuzzy_init( marker: enumerate_variant_windows(targets[marker], tag_length) for marker in unresolved } - _INFER_STATE["leading_anchor"] = leading_anchor seed_length = max(12, min(18, tag_length // 3)) offsets = sorted({*range(0, tag_length - seed_length + 1, seed_length), tag_length - seed_length}) seeds: Dict[str, set] = {} @@ -1341,6 +1734,8 @@ def _infer_fuzzy_init( "offsets": offsets, "seed_length": seed_length, "sinks": tuple(sink_tags), + # Stored with the rest, after the clear, so the fuzzy pass cuts raw reads as the exact pass does. + "leading_anchor": leading_anchor, } ) @@ -1815,9 +2210,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)) @@ -1870,6 +2265,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.""" @@ -1878,6 +2278,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)) @@ -1907,41 +2308,109 @@ 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 = (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) + 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]: + """Where the amplicon starts in a raw read: ``(cut, mismatches)``, or ``(-1, 0)``. + + The anchor must end within LEADING_ANCHOR_SEARCH bases beyond its own + length. Its first exact occurrence wins. Only when there is none, and + ``max_mismatches`` is 1, may one placement within a single substitution + stand in — and only when it is the one such placement in the window, so a + read never gets a guessed cut. The match counts substitutions only, but + an indel in the anchor's last base reads as one substitution there, and + the cut is then one base off. Such a read starts a base early or late, + and the primer match that follows usually rejects it. A + sequencing error in the anchor is upstream of the amplicon, so the reads + this recovers carry no allele bias. An anchor shorter than + LEADING_ANCHOR_MISMATCH_MIN_LENGTH is always matched exactly, because + fewer bases match unrelated sequence by chance. Candidates come from + the pigeonhole principle (with one substitution, one half of the anchor + still matches exactly), so the search stays in ``str.find``. + """ + width = len(anchor) + search_end = width + LEADING_ANCHOR_SEARCH + start = sequence.find(anchor, 0, search_end) + if start >= 0: + return start + width, 0 + if max_mismatches <= 0 or width < LEADING_ANCHOR_MISMATCH_MIN_LENGTH: + return -1, 0 + last_start = min(search_end, len(sequence)) - width + if last_start < 0: + return -1, 0 + half = width // 2 + placements = set() + for offset, piece in ((0, anchor[:half]), (half, anchor[half:])): + end = last_start + offset + len(piece) + position = sequence.find(piece, offset, end) + while position >= 0: + candidate = position - offset + if candidate not in placements and tag_mismatches(sequence[candidate:candidate + width], anchor, stop_after=1) <= 1: + placements.add(candidate) + position = sequence.find(piece, position + 1, end) + if len(placements) != 1: + return -1, 0 + return placements.pop() + width, 1 def fastq_records(path: Path, leading_anchor: str = "") -> Iterator[Tuple[str, str]]: """``(sequence, quality)`` records. With ``leading_anchor`` (raw deliveries that keep the library's common sequence in front of the amplicon) each - read starts where the anchor ends, and reads without it are skipped; - callers that must count those reads cut for themselves (``process_sample``).""" - search_end = len(leading_anchor) + LEADING_ANCHOR_SEARCH + read starts where an exact copy of the anchor ends, and reads without one + are skipped. ``process_sample`` cuts for itself: it counts the reads it + skips and may match the anchor with a substitution.""" with open_text(path, "rt") as handle: record_number = 0 while True: @@ -1961,31 +2430,34 @@ def fastq_records(path: Path, leading_anchor: str = "") -> Iterator[Tuple[str, s if len(sequence) != len(quality): raise MadcError(f"Sequence/quality length mismatch at FASTQ record {record_number} in {path}") if leading_anchor: - cut = sequence.find(leading_anchor, 0, search_end) + cut, _ = locate_leading_anchor(sequence, leading_anchor) if cut < 0: continue - cut += len(leading_anchor) sequence, quality = sequence[cut:], quality[cut:] yield sequence, quality LEADING_ANCHOR_PREFIX = 15 # bases of a panel tag that identify where the amplicon starts in a read -LEADING_ANCHOR_SAMPLE = 2000 # reads of the first FASTQ inspected by the raw-delivery check +LEADING_ANCHOR_SAMPLE = 2000 # reads inspected by the raw-delivery check, split evenly over the sampled FASTQs LEADING_ANCHOR_MIN_LENGTH = 8 # a detected anchor must be at least this long -LEADING_ANCHOR_FILES = 8 # FASTQs the check samples, so per-sample barcodes vary and only the shared part survives +LEADING_ANCHOR_FILES = 24 # FASTQs the check samples: each has its own barcode, and the anchor is what they all share +LEADING_ANCHOR_MIN_FILES = 3 # with fewer, barcode bases the files happen to share cannot be told from the anchor def detect_leading_anchor(fastqs: Sequence[Path], tag_prefixes: Set[str], sample_reads: int = LEADING_ANCHOR_SAMPLE) -> Dict[str, object]: """Do these FASTQs look like a raw delivery, with a constant sequence in front of every amplicon? A read is *anchored* when a panel tag begins at its first base and *shifted* when a panel tag begins further in; the - bases before a shifted tag are barcode plus common sequence, and the - anchor is the suffix that at least 90% of those prefixes share. Reads - are sampled from several files because an inline barcode is constant - within a sample and must not be mistaken for the common sequence.""" + bases before a shifted tag are an inline barcode plus the common + sequence. The barcode is constant within a file and differs between + files, in length too, so each file gives one prefix, the most common + among its shifted reads, and the anchor is the longest suffix those + prefixes share. With a single file that is the whole prefix, barcode + included (``anchor_files`` says how many files defined the anchor).""" anchored = shifted = sampled = 0 - prefixes: List[str] = [] offsets: Counter = Counter() + file_prefixes: List[Tuple[str, int]] = [] # per file: its prefix, and the shifted reads behind it + file_offsets: List[int] = [] search = LEADING_ANCHOR_PREFIX + LEADING_ANCHOR_SEARCH + 20 # Spread the sample across the run: neighbouring files often share a # plate and part of their barcode, which must not be read as anchor. @@ -1996,6 +2468,8 @@ def detect_leading_anchor(fastqs: Sequence[Path], tag_prefixes: Set[str], sample per_file = max(1, sample_reads // max(1, len(files))) for fastq in files: taken = 0 + prefixes: Counter = Counter() + reads: List[str] = [] for sequence, _quality in fastq_records(Path(fastq)): sampled += 1 taken += 1 @@ -2005,42 +2479,59 @@ def detect_leading_anchor(fastqs: Sequence[Path], tag_prefixes: Set[str], sample for offset in range(1, min(len(sequence) - LEADING_ANCHOR_PREFIX, search)): if sequence[offset:offset + LEADING_ANCHOR_PREFIX] in tag_prefixes: shifted += 1 - prefixes.append(sequence[:offset]) + prefixes[sequence[:offset]] += 1 + reads.append(sequence) offsets[offset] += 1 break if taken >= per_file: break + # The file's prefix is its most common one, seen at least twice. + # That sets aside sequencing errors, and a tag found a base or two + # early: a candidate window that happens to begin with the last + # bases of the anchor (chance 1 in 4 per base). + prefix, count = prefixes.most_common(1)[0] if prefixes else ("", 0) + if count < 2: + continue + file_offsets.append(len(prefix)) + # A file that mixes barcodes has no prefix of its own: shorten the + # most common one until 90% of its shifted reads would be cut by it, + # which leaves what those barcodes share. + while prefix and sum(read.find(prefix, 0, len(prefix) + LEADING_ANCHOR_SEARCH) >= 0 for read in reads) < 0.9 * len(reads): + prefix = prefix[1:] + if len(prefix) >= LEADING_ANCHOR_MIN_LENGTH: + file_prefixes.append((prefix, len(reads))) anchor = "" + agreeing: List[str] = [] + if file_prefixes: + # Files holding 90% of the shifted reads must end in the same bases, + # so one failed sample does not hide the anchor. Among the files that + # do, every one must agree on each further base: a base that even one + # of them lacks is barcode, and an anchor that kept it would lose + # every read of the samples without it. + endings: Counter = Counter() + for prefix, reads_behind in file_prefixes: + endings[prefix[-LEADING_ANCHOR_MIN_LENGTH:]] += reads_behind + ending, support = endings.most_common(1)[0] + if support >= 0.9 * sum(endings.values()): + agreeing = [prefix for prefix, _reads_behind in file_prefixes if prefix.endswith(ending)] + anchor = os.path.commonprefix([prefix[::-1] for prefix in agreeing])[::-1] modal_offset = offsets.most_common(1)[0][0] if offsets else None - if prefixes: - # The amplicon starts at the modal offset; a tag found a base or two - # earlier is a candidate window that happens to begin with the same - # base as the prefix (chance 1 in 4 per base), so only prefixes of - # the modal length define the anchor. - modal_prefixes = [prefix for prefix in prefixes if len(prefix) == modal_offset] - length = 1 - while modal_prefixes and length <= modal_offset: - suffix, count = Counter(prefix[-length:] for prefix in modal_prefixes).most_common(1)[0] - if count < 0.9 * len(modal_prefixes): - break - anchor = suffix - length += 1 - if len(anchor) < LEADING_ANCHOR_MIN_LENGTH: - anchor = "" return { "fastqs": [str(fastq) for fastq in files], "reads_sampled": sampled, "anchored_rate": anchored / max(1, sampled), "shifted_rate": shifted / max(1, sampled), "offset": modal_offset, + "offsets": (min(file_offsets), max(file_offsets)) if file_offsets else None, "anchor": anchor, + "anchor_files": len(agreeing), } def resolve_leading_anchor(args: argparse.Namespace, fastqs: Sequence[Path], tag_prefixes: Set[str], command: str) -> str: """Settle ``--leading-anchor`` before any read pass: an explicit sequence - is used as given; ``auto`` detects it from the first FASTQ; with no - option the first FASTQ is still checked, and a run that would assign + is used as given; ``auto`` detects it from a sample of the FASTQs; with + no option the same sample is still checked, and a run that would assign almost nothing because the reads carry a constant prefix stops and names the anchor to use, rather than producing an empty table.""" value = getattr(args, "leading_anchor", None) @@ -2051,6 +2542,13 @@ def resolve_leading_anchor(args: argparse.Namespace, fastqs: Sequence[Path], tag report = detect_leading_anchor([Path(fastq) for fastq in fastqs], tag_prefixes) where = Path(fastqs[0]).name + (f" and {len(report['fastqs']) - 1} more" if len(report["fastqs"]) > 1 else "") looks_raw = report["shifted_rate"] >= 0.5 and report["anchored_rate"] < 0.05 and report["anchor"] + # Barcodes differ in length, so the tag starts at a range of offsets. + low, high = report["offsets"] or (report["offset"], report["offset"]) + tag_start = f"tag start at offset {low}" + (f" to {high}" if high != low else "") + # From one or two files the anchor may keep barcode bases they share. + # It still cuts these files correctly, so it is used, and flagged. + few = report["anchor"] and report["anchor_files"] < LEADING_ANCHOR_MIN_FILES + files_behind = f"{report['anchor_files']} FASTQ{'s' if report['anchor_files'] != 1 else ''}" if value and value.lower() == "auto": if not report["anchor"] or report["shifted_rate"] < 0.5: raise MadcError( @@ -2062,16 +2560,26 @@ def resolve_leading_anchor(args: argparse.Namespace, fastqs: Sequence[Path], tag args.leading_anchor_detected = True print( f"{command}: leading anchor {report['anchor']} detected in {where} " - f"(tag start at offset {report['offset']} in {report['shifted_rate']:.0%} of {report['reads_sampled']} reads)", + f"({tag_start}, in {report['shifted_rate']:.0%} of {report['reads_sampled']} reads)", file=sys.stderr, ) + if few: + print( + f"warning: the leading anchor was detected from {files_behind}, too few to tell the common sequence " + "from the sample barcode in front of it; it fits these reads, but do not reuse it for other samples", + file=sys.stderr, + ) return report["anchor"] if looks_raw: + caution = ( + f"; with {files_behind} that prefix may include the sample barcode, so it fits these files only" + if few else "" + ) raise MadcError( - f"{command}: {where} looks like a raw delivery: {report['shifted_rate']:.0%} of the first " - f"{report['reads_sampled']} reads carry a panel tag after a constant prefix ending in {report['anchor']} " - f"(tag start at offset {report['offset']}), and {report['anchored_rate']:.0%} start with one; rerun with " - f"--leading-anchor {report['anchor']} (or --leading-anchor auto)" + f"{command}: {where} looks like a raw delivery: {report['shifted_rate']:.0%} of " + f"{report['reads_sampled']} sampled reads carry a panel tag after a constant prefix ending in {report['anchor']} " + f"({tag_start}), and {report['anchored_rate']:.0%} start with one; rerun with " + f"--leading-anchor {report['anchor']} (or --leading-anchor auto){caution}" ) return "" @@ -2128,7 +2636,20 @@ def _load_cache(path: Path, sample: Sample, source_stat: os.stat_result) -> Opti # invalidates its cache without any content hashing on the hot path. if payload["source_size"] != source_stat.st_size or payload["source_mtime_ns"] != source_stat.st_mtime_ns: return None - counts = {(int(marker), sequence): int(count) for marker, sequence, count in payload["counts"]} + # A counts entry is [marker, tag, reads], followed by [bases, reads] for each continuation kept. + counts = {(int(marker), sequence): int(count) for marker, sequence, count, *_ in payload["counts"]} + continuations = { + (int(marker), sequence): [(bases, int(reads)) for bases, reads in kept] + for marker, sequence, _, *kept in payload["counts"] + if kept + } + continuation_residuals = { + (int(marker), sequence): [ + (prefix, int(read_length), int(reads)) for prefix, read_length, reads in entries + ] + for marker, sequence, *entries in payload.get("continuation_residuals", ()) + if entries + } quality_support = { (int(marker), sequence): tuple(int(value) for value in values) for marker, sequence, *values in payload["quality_support"] @@ -2149,19 +2670,26 @@ def _load_cache(path: Path, sample: Sample, source_stat: os.stat_result) -> Opti partial_quality_support=partial_quality_support, qc=payload["qc"], cache_hit=True, + continuations=continuations, + continuation_residuals=continuation_residuals, ) except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError): 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 = { + payload: Dict[str, object] = { "source_size": source_stat.st_size, "source_mtime_ns": source_stat.st_mtime_ns, "qc": result.qc, - "counts": [[marker, sequence, count] for (marker, sequence), count in result.counts.items()], + "counts": [ + [marker, sequence, count, *result.continuations.get((marker, sequence), ())] + for (marker, sequence), count in result.counts.items() + ], "quality_support": [ [marker, sequence, *values] for (marker, sequence), values in result.quality_support.items() @@ -2175,18 +2703,147 @@ def _write_cache(path: Path, result: SampleResult, source_stat: os.stat_result) for (marker, sequence), values in result.partial_quality_support.items() ], } - with gzip.open(temporary, "wt") as handle: + if result.continuation_residuals: + payload["continuation_residuals"] = [ + [marker, sequence, *entries] + for (marker, sequence), entries in result.continuation_residuals.items() + ] + with gzip.open(temporary, "wt", compresslevel=gzip_level) as handle: json.dump(payload, handle, separators=(",", ":")) temporary.replace(path) -def select_marker( +def same_tag_window(a: Locus, b: Locus) -> bool: + """Do two markers read the same tag window of one amplicon? + + True when their Ref tags have the same length and are IUPAC-compatible + at every position other than the two markers' own variant positions. That + is what a DArTag tile looks like: tiles share a left primer (or one + primer extends the other), and each tile's tag carries the neighbouring + tiles' SNPs as ambiguity codes, so every read from the amplicon fits each + tile's tags equally well. normalize-reads tiles excise different + windows of their locus and never pass. + """ + if a.index == b.index or len(a.ref_tag) != len(b.ref_tag): + return False + exempt = (a.variant_pos, b.variant_pos) + return all( + position in exempt or bases_compatible(left, right) + for position, (left, right) in enumerate(zip(a.ref_tag, b.ref_tag)) + ) + + +def _declared_locus_groups(loci: Sequence[Locus]) -> Dict[int, str]: + """Effective declared LocusGroup per marker index (empty string when undeclared). + + ``write_reference_tags`` leaves ``LocusGroup`` blank when a group's leader + marker shares its name with the group (``Locus.group`` restores it). A + marker is therefore declared in ``locus.group`` whenever its ``locus_group`` + cell is set or another marker in the panel names ``locus.marker`` as its + ``locus_group``. + """ + named = {locus.locus_group for locus in loci if locus.locus_group} + return { + locus.index: (locus.group if (locus.locus_group or locus.marker in named) else "") + for locus in loci + } + + +def tile_families(loci: Sequence[Locus], mode: str = "auto") -> Tuple[Tuple[int, ...], ...]: + """Markers whose reads ``generate`` credits together (``--tile-groups``). + + Two markers are linked when they read the same tag window + (``same_tag_window``) and one's primer matches the start of the other's + tag, so one read reaches both; a family is a connected set of links. + ``declared`` links only markers that share a ``LocusGroup``; ``auto`` + also links undeclared markers, but never two + markers declared in different groups (including through an undeclared + bridge); ``off`` links none. Families are sorted tuples of marker + indices, members of two or more only. + """ + if mode == "off": + return () + primer_index = PrimerIndex(loci) + declared_of = _declared_locus_groups(loci) + + def build_components(allowed: Set[int], declared_only: bool) -> List[List[int]]: + parent = {index: index for index in allowed} + + def root(index: int) -> int: + while parent[index] != index: + parent[index] = parent[parent[index]] + index = parent[index] + return index + + for index in sorted(allowed): + locus = loci[index] + left_group = declared_of[index] + for other in primer_index.match(locus.ref_tag): + if other not in parent: + continue + right_group = declared_of[other] + same_declared = bool(left_group) and left_group == right_group + conflicting = bool(left_group and right_group) and not same_declared + if not (same_declared or (not declared_only and not conflicting)): + continue + if same_tag_window(locus, loci[other]): + parent[root(other)] = root(index) + grouped: Dict[int, List[int]] = defaultdict(list) + for index in sorted(allowed): + grouped[root(index)].append(index) + return [group for group in grouped.values() if len(group) > 1] + + components = build_components(set(range(len(loci))), declared_only=(mode == "declared")) + if mode == "auto": + resolved: List[List[int]] = [] + for group in components: + groups_present = {declared_of[index] for index in group if declared_of[index]} + if len(groups_present) <= 1: + resolved.append(group) + else: + # An undeclared marker bridged two declared groups: keep only declared links. + resolved.extend(build_components(set(group), declared_only=True)) + components = resolved + 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 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): + continue + if best is None or edits < best: + best = edits + return best + + +def select_markers( tag: str, candidates: Sequence[int], loci: Sequence[Locus], max_mismatches: int, gap_band: int = 0, -) -> Tuple[Optional[int], str]: + family_of: Optional[Mapping[int, Tuple[int, ...]]] = None, +) -> Tuple[Tuple[int, ...], str]: """Resolve primer candidates by identity to the available tag prefix. Substitution-only identity decides first and is never overturned. When @@ -2199,7 +2856,16 @@ def select_marker( (few substitutions, few gap events); a co-amplified paralog reaches the budget through many substitutions and stays off-target. A cheap exact lower bound (``gapped_prescreen``) skips the alignment for hopeless tags. + + The best-fitting marker takes the read alone, and a tie is dropped as + ambiguous. The exception is a tie in which every marker belongs to one + tile family (``family_of``, from ``tile_families``). Tiles read one + amplicon, so the read is then credited to every family member it fits + within the budget (substitution-only, or by one gapped reading), as + running each tile in a panel of its own would. A tie that crosses + families stays ambiguous. """ + family_of = family_of or {} scored = [] for marker_index in candidates: locus = loci[marker_index] @@ -2212,34 +2878,69 @@ def select_marker( ) scored.append((distance, marker_index)) scored.sort() + + def credited(ranked: Sequence[Tuple[int, int]]) -> Optional[Tuple[int, ...]]: + best_distance, best_marker = ranked[0] + family = family_of.get(best_marker, (best_marker,)) + if any(distance == best_distance and marker not in family for distance, marker in ranked): + return None + if len(family) == 1: + return (best_marker,) + members = [marker for distance, marker in ranked if marker in family and distance <= max_mismatches] + if gap_band > 0: + fitted = set(members) + members += [ + marker for _, marker in ranked + if marker in family and marker not in fitted + and _gapped_edits(tag, loci[marker], max_mismatches, gap_band) is not None + ] + return tuple(sorted(members)) + if scored and scored[0][0] <= max_mismatches: - if len(scored) > 1 and scored[0][0] == scored[1][0]: - return None, "ambiguous" - return scored[0][1], "assigned" + markers = credited(scored) + return (markers, "assigned") if markers else ((), "ambiguous") if gap_band <= 0 or not scored: - return None, "offtarget" + return (), "offtarget" gapped = [] for marker_index in candidates: - locus = loci[marker_index] - best: 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: - 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): - continue - if best is None or edits < best: - best = edits - if best is not None: - gapped.append((best, marker_index)) + edits = _gapped_edits(tag, loci[marker_index], max_mismatches, gap_band) + if edits is not None: + gapped.append((edits, marker_index)) gapped.sort() if not gapped: - return None, "offtarget" - if len(gapped) > 1 and gapped[0][0] == gapped[1][0]: - return None, "ambiguous" - return gapped[0][1], "assigned_gapped" + return (), "offtarget" + markers = credited(gapped) + return (markers, "assigned_gapped") if markers else ((), "ambiguous") + + +def select_marker( + tag: str, + candidates: Sequence[int], + loci: Sequence[Locus], + max_mismatches: int, + gap_band: int = 0, +) -> Tuple[Optional[int], str]: + """``select_markers`` without tile families: the one marker a read goes to, or + ``None`` with the reason it went nowhere.""" + markers, status = select_markers(tag, candidates, loci, max_mismatches, gap_band) + 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. The tag and the sequence must have one length, which + the caller checks. + """ + 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( @@ -2268,12 +2969,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: @@ -2300,12 +3013,152 @@ def add_quality_support( support[key][quality_index] += 1 +def keeps_continuation(locus: Locus, tag: str, gap_band: int) -> bool: + """Whether the read pass keeps the bases that follow ``tag`` in its reads. + + Only row_decision uses them, and only for a row whose target lies in + an unresolved end. It compares such a row with the two canonical tags, + so theirs are kept too.""" + if gap_band <= 0: + return False + return tag in (locus.ref_tag, locus.alt_tag) or _target_unread( + locus, _row_decision(locus.ref_tag, locus.alt_tag, tag, gap_band, GAP_VERIFIED_SUFFIX, False) + ) + + +def _reached_length(reads_by_length: Counter) -> int: + """Longest continuation length reached by CONTINUATION_REACHED_BY of reads.""" + all_reads = sum(reads_by_length.values()) + if not all_reads: + return 0 + reaching = 0 + for candidate in sorted(reads_by_length, reverse=True): + reaching += reads_by_length[candidate] + if reaching >= CONTINUATION_REACHED_BY * all_reads: + return candidate + return 0 + + +def pooled_continuations(results: Sequence[SampleResult]) -> Tuple[Dict[int, Dict[str, str]], int]: + """What follows each tag across the cohort: ``({marker index: {tag: bases}}, length)``. + + Reads end at different places, so one continuation arrives at several + lengths. Each tag's continuations are cut to the longest length that + CONTINUATION_REACHED_BY of that tag's reads reach, so unrelated markers or + longer-read tags never drop a shorter-read tag's continuation; reads that + stop short of that length are left out. A tag has a continuation when its + commonest sequence has CONTINUATION_MIN_READS reads and + CONTINUATION_MIN_SHARE of all continuation-bearing reads of that tag at + that length (including ``continuation_residuals``, which preserve both + read length and any shared prefix of at least GAP_VERIFIED_SUFFIX bases + with a kept continuation). The returned ``length`` is the cohort-wide + length for QC reporting. + """ + found: Dict[Tuple[int, str], Counter] = defaultdict(Counter) + residuals: Dict[Tuple[int, str], List[Tuple[str, int, int]]] = defaultdict(list) + lengths_by_key: Dict[Tuple[int, str], Counter] = defaultdict(Counter) + all_lengths: Counter = Counter() + for result in results: + for key, kept in result.continuations.items(): + for bases, reads in kept: + found[key][bases] += reads + lengths_by_key[key][len(bases)] += reads + all_lengths[len(bases)] += reads + for key, entries in result.continuation_residuals.items(): + for prefix, read_length, reads in entries: + residuals[key].append((prefix, read_length, reads)) + lengths_by_key[key][read_length] += reads + all_lengths[read_length] += reads + pooled: Dict[int, Dict[str, str]] = defaultdict(dict) + for (marker_index, tag), counts in found.items(): + key = (marker_index, tag) + tag_length = _reached_length(lengths_by_key[key]) + if not tag_length: + continue + at_length: Counter = Counter() + total_at_length = 0 + for bases, reads in counts.items(): + if len(bases) >= tag_length: + total_at_length += reads + at_length[bases[:tag_length]] += reads + for prefix, read_length, reads in residuals.get(key, ()): + if read_length >= tag_length: + total_at_length += reads + if len(prefix) >= tag_length: + at_length[prefix[:tag_length]] += reads + if not at_length: + continue + bases, reads = at_length.most_common(1)[0] + if reads >= CONTINUATION_MIN_READS and reads >= CONTINUATION_MIN_SHARE * total_at_length: + pooled[marker_index][tag] = bases + return dict(pooled), _reached_length(all_lengths) + + +def _shared_prefix_length(a: str, b: str) -> int: + limit = min(len(a), len(b)) + for index in range(limit): + if a[index] != b[index]: + return index + return limit + + +def _compact_continuations(found: Counter) -> Tuple[List[Tuple[str, int]], List[Tuple[str, int, int]]]: + """Collapse prefix-compatible length variants into families, keep the top + CONTINUATIONS_KEPT families with all their exact lengths, and summarize + remaining sequences as ``(shared_prefix, read_length, reads)`` residuals. + + Keeping all length variants of each kept family prevents one biological + sequence arriving at several read lengths from overflowing the cap. + Recording the longest shared prefix (>= GAP_VERIFIED_SUFFIX) for residual + reads ensures sequences that agree through the pooled length (e.g. noisy + 3' poly-G tails past the read end) still count toward their sequence while + keeping exact denominators at every length. + """ + families: List[List] = [] # [longest_representative, Counter({length: reads})] + for bases, reads in sorted(found.items(), key=lambda item: (-item[1], -len(item[0]), item[0])): + for family in families: + rep = family[0] + if rep.startswith(bases) or bases.startswith(rep): + if len(bases) > len(rep): + family[0] = bases + family[1][len(bases)] += reads + break + else: + families.append([bases, Counter({len(bases): reads})]) + families.sort(key=lambda fam: (-sum(fam[1].values()), -len(fam[0]), fam[0])) + kept_families = families[:CONTINUATIONS_KEPT] + reps = [rep for rep, _ in kept_families] + kept = [ + (rep[:length], reads) + for rep, lengths in kept_families + for length, reads in sorted(lengths.items(), reverse=True) + ] + residual_counts: Counter = Counter() + for rep_other, lengths_other in families[CONTINUATIONS_KEPT:]: + best_prefix = "" + for rep in reps: + shared = _shared_prefix_length(rep_other, rep) + if shared >= GAP_VERIFIED_SUFFIX and shared > len(best_prefix): + best_prefix = rep[:shared] + for read_length, reads in lengths_other.items(): + prefix = best_prefix[:read_length] if len(best_prefix) >= GAP_VERIFIED_SUFFIX else "" + if len(prefix) < GAP_VERIFIED_SUFFIX: + prefix = "" + residual_counts[(prefix, read_length)] += reads + residuals = [ + (prefix, read_length, reads) + for (prefix, read_length), reads in sorted(residual_counts.items()) + ] + return kept, residuals + + def process_sample( sample: Sample, loci: Sequence[Locus], 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. @@ -2313,13 +3166,23 @@ def process_sample( accepted for exactly one locus when its tag lies within the identity envelope of that locus's Ref/Alt tags, or — when every candidate rejects it and ``settings.gap_band`` is positive — under one gapped reading within the - same edit budget (``select_marker``); ambiguous reads are dropped rather - than guessed. Tags carrying an N are resolved at the end of the sample + same edit budget (``select_markers``); ambiguous reads are dropped rather + than guessed. The one exception is a tile family + (``settings.tile_families``): a read that fits several tiles of one + amplicon is credited to each of them, ``reads_assigned`` still counts it + once, and the credits beyond the first are counted in + ``tile_extra_credits`` (``partial_tile_extra_credits`` for reads shorter + than the tag). Tags carrying an N are resolved at the end of the sample (``resolve_n_tags``) and never counted as haplotypes of their own. Alongside each count, a per-threshold vector of whole-tag-clean read tallies is kept so quality thresholds can change later without touching the FASTQs again. Reads shorter than the tag are collected separately for the optional partial-read stage. + + A read longer than the tag also shows what follows it. For the tags + row_decision can use that for (keeps_continuation), those continuations + are counted once the sample has CONTINUATION_MIN_READS reads of the tag, + the earlier ones included, so the order of the reads changes nothing. """ fastq_path = Path(sample.fastq) source_stat = fastq_path.stat() @@ -2340,18 +3203,25 @@ def process_sample( # Amplicon reads repeat heavily, so the (deterministic) assignment decision # is memoized per unique sequence once a primer candidate list was found; # primer-less reads fail the trie walk cheaply and are not worth storing. - full_decisions: Dict[str, Tuple[Optional[int], str]] = {} - partial_decisions: Dict[str, Tuple[Optional[int], str]] = {} + full_decisions: Dict[str, Tuple[Tuple[int, ...], str]] = {} + partial_decisions: Dict[str, Tuple[Tuple[int, ...], str]] = {} + continuations: Dict[Tuple[int, str], Counter] = defaultdict(Counter) + pending_continuations: Dict[str, List[str]] = {} # first two continuations buffered per tag until read #3 + keepers: Dict[str, Tuple[int, ...]] = {} # per tag, the markers that keep its continuation + family_of = {member: family for family in settings.tile_families for member in family} for sequence, quality in fastq_records(fastq_path): qc["reads_total"] += 1 if settings.leading_anchor: # Raw deliveries that keep the library's common sequence in front # of the amplicon: the read starts where that anchor ends. - cut = sequence.find(settings.leading_anchor, 0, len(settings.leading_anchor) + LEADING_ANCHOR_SEARCH) + cut, anchor_mismatches = locate_leading_anchor( + sequence, settings.leading_anchor, settings.leading_anchor_mismatches + ) if cut < 0: qc["reads_no_leading_anchor"] += 1 continue - cut += len(settings.leading_anchor) + if anchor_mismatches: + qc["reads_leading_anchor_mismatch"] += 1 sequence, quality = sequence[cut:], quality[cut:] if len(sequence) < settings.tag_length: if settings.partial_min_length <= 0 or len(sequence) < settings.partial_min_length: @@ -2366,21 +3236,19 @@ def process_sample( partial_max_mismatches = math.floor( settings.max_offtarget_mismatches * len(sequence) / settings.tag_length ) - marker_index, status = select_marker( - sequence, candidates, loci, partial_max_mismatches - ) - decision = ( - marker_index, - "reads_partial" if marker_index is not None else f"reads_partial_{status}", + markers, status = select_markers( + sequence, candidates, loci, partial_max_mismatches, family_of=family_of ) + decision = (markers, "reads_partial" if markers else f"reads_partial_{status}") partial_decisions[sequence] = decision - marker_index, qc_key = decision + markers, qc_key = decision qc[qc_key] += 1 - if marker_index is None: - continue - key = (marker_index, sequence) - partial_counts[key] += 1 - add_quality_support(partial_quality_support, key, quality) + if len(markers) > 1: + qc["partial_tile_extra_credits"] += len(markers) - 1 + for marker_index in markers: + key = (marker_index, sequence) + partial_counts[key] += 1 + add_quality_support(partial_quality_support, key, quality) continue tag = sequence[:settings.tag_length] decision = full_decisions.get(tag) @@ -2389,23 +3257,58 @@ def process_sample( if not candidates: qc["reads_no_primer"] += 1 continue - marker_index, status = select_marker(tag, candidates, loci, settings.max_offtarget_mismatches, settings.gap_band) - decision = (marker_index, status) + decision = select_markers( + tag, candidates, loci, settings.max_offtarget_mismatches, settings.gap_band, family_of + ) full_decisions[tag] = decision - marker_index, status = decision - if marker_index is None: + markers, status = decision + if not markers: qc[f"reads_{status}"] += 1 continue qc["reads_assigned"] += 1 if status == "assigned_gapped": qc["reads_assigned_gapped"] += 1 - key = (marker_index, tag) - exact_counts[key] += 1 - add_quality_support(exact_quality_support, key, quality[:settings.tag_length]) + if len(markers) > 1: + qc["tile_extra_credits"] += len(markers) - 1 + for marker_index in markers: + key = (marker_index, tag) + exact_counts[key] += 1 + add_quality_support(exact_quality_support, key, quality[:settings.tag_length]) + # Buffer a tag's first two continuations and decide whether to keep them only at read #3: + # singleton/doubleton error tags pay no alignment cost, while real tags keep all reads. + if settings.gap_band > 0: + continuation = sequence[settings.tag_length : settings.tag_length + CONTINUATION_BASES] + if len(continuation) >= GAP_VERIFIED_SUFFIX: + seen = exact_counts[(markers[0], tag)] + if seen < CONTINUATION_MIN_READS: + pending_continuations.setdefault(tag, []).append(continuation) + else: + if tag not in keepers: + keepers[tag] = tuple( + marker_index for marker_index in markers + if keeps_continuation(loci[marker_index], tag, settings.gap_band) + ) + buffered = pending_continuations.pop(tag, ()) + for marker_index in keepers[tag]: + for earlier in buffered: + continuations[(marker_index, tag)][earlier] += 1 + for marker_index in keepers[tag]: + continuations[(marker_index, tag)][continuation] += 1 resolve_n_tags(exact_counts, exact_quality_support, loci, qc) qc["unique_full_tags_raw"] = len(exact_counts) qc["unique_partial_tags_raw"] = len(partial_counts) + # A tag with an N is counted under the tag it resolves to and keeps no continuation. + kept_continuations: Dict[Tuple[int, str], List[Tuple[str, int]]] = {} + continuation_residuals: Dict[Tuple[int, str], List[Tuple[str, int, int]]] = {} + for key, found in continuations.items(): + if key not in exact_counts: + continue + kept, residuals = _compact_continuations(found) + if kept: + kept_continuations[key] = kept + if residuals: + continuation_residuals[key] = residuals result = SampleResult( sample=sample, counts=dict(exact_counts), @@ -2416,14 +3319,27 @@ def process_sample( }, qc=dict(qc), cache_hit=False, + continuations=kept_continuations, + 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 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]: @@ -2604,12 +3520,37 @@ 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]: - """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]) @@ -2619,6 +3560,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]]: @@ -2631,6 +3574,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()} @@ -2716,6 +3661,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 @@ -2804,12 +3750,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] @@ -2818,17 +3763,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) @@ -2900,6 +3846,7 @@ def _pooled_moves( max_distance: int, alpha: float, gap_band: int, + continuations: Optional[Mapping[str, str]] = None, ) -> Dict[str, str]: """One locus of the pooled pass: the project-wide skew names a parent for every evidence-failing sequence, and the move is kept only when the parent @@ -2910,7 +3857,9 @@ def _pooled_moves( def group(sequence: str) -> str: if sequence not in groups: - groups[sequence] = ALLELE_GROUP.get(classify_sequence(locus, sequence, gap_band), "other") + groups[sequence] = ALLELE_GROUP.get( + classify_sequence(locus, sequence, gap_band, continuations), "other" + ) return groups[sequence] return { @@ -2924,32 +3873,51 @@ def group(sequence: str) -> str: def _pooled_init( - loci: Sequence[Locus], protected: Mapping[int, set[str]], max_distance: int, alpha: float, gap_band: int + loci: Sequence[Locus], + protected: Mapping[int, set[str]], + max_distance: int, + alpha: float, + gap_band: int, + continuations: Mapping[int, Mapping[str, str]], ) -> None: _POOLED_STATE.clear() - _POOLED_STATE.update(loci=loci, protected=protected, max_distance=max_distance, alpha=alpha, gap_band=gap_band) + _POOLED_STATE.update( + loci=loci, + protected=protected, + max_distance=max_distance, + alpha=alpha, + gap_band=gap_band, + continuations=continuations, + ) def _pooled_worker(item: Tuple[int, Dict[str, int]]) -> Tuple[int, Dict[str, str]]: marker_index, sequence_counts = item loci = _POOLED_STATE["loci"] # type: ignore[assignment] protected = _POOLED_STATE["protected"] # type: ignore[assignment] + continuations = _POOLED_STATE["continuations"] # type: ignore[assignment] return marker_index, _pooled_moves( loci[marker_index], sequence_counts, protected.get(marker_index, ()), # type: ignore[index,attr-defined] _POOLED_STATE["max_distance"], _POOLED_STATE["alpha"], _POOLED_STATE["gap_band"], # type: ignore[arg-type] + continuations.get(marker_index), # type: ignore[attr-defined] ) def finalize_counts( - sample_results: Sequence[SampleResult], + sample_results: MutableSequence[SampleResult], loci: Sequence[Locus], denoise: DenoiseSettings, 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 @@ -2978,6 +3946,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; @@ -2986,22 +3958,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 + # 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 @@ -3009,14 +3985,14 @@ def _stage(label: str) -> None: # over the workers; the panel and protected set travel once per worker. with concurrent.futures.ProcessPoolExecutor( max_workers=jobs, initializer=_pooled_init, - initargs=(loci, protected, denoise.global_distance, denoise.alpha, gap_band), + initargs=(loci, protected, denoise.global_distance, denoise.alpha, gap_band, pooled_after_tag), ) as executor: moves = dict(executor.map(_pooled_worker, aggregate.items(), chunksize=16)) else: for marker_index, sequence_counts in aggregate.items(): moves[marker_index] = _pooled_moves( loci[marker_index], sequence_counts, protected.get(marker_index, ()), - denoise.global_distance, denoise.alpha, gap_band, + denoise.global_distance, denoise.alpha, gap_band, pooled_after_tag.get(marker_index), ) finalized = [] for result in sample_denoised: @@ -3077,7 +4053,7 @@ def _reading(sequence: str, template: str, gap_band: int, guard: bool = True) -> return _reading_from_ops(sequence, template, ops, end_read, end_ref, edits) -def marker_type_label(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT, events=None) -> str: +def marker_type_label(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT, events=None, designed=None) -> str: """What a row carries beyond its canonical: '.', 'snp', 'indel' or 'both'. Derived from the row's Variants (variant_events, always against the Ref @@ -3088,16 +4064,19 @@ def marker_type_label(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFA inherited indel and the SNP. 'snp' = substitutions only, 'indel' = gaps only, 'both' = gaps plus substitutions, '.' = no concrete event beyond the canonical (the Ref row; a row that merely realises an - ambiguity code). Downstream users can keep or drop undesigned indel - haplotypes by this label alone. ``events`` may be passed when already - computed. + ambiguity code), 'unresolved' = the row's end is not read + (row_decision), whatever the row carries before it: a gap there is + likely but unverified. Downstream users can keep or drop undesigned + indel haplotypes by this label alone. ``events`` may be passed when already + computed, and ``designed`` (the Alt row's events) when the caller knows + more than the two tags show, as for a marker written without primers. """ if sequence == locus.ref_tag: return "." if events is None: events = variant_events(locus, sequence, gap_band) if sequence != locus.alt_tag: - designed = Counter(_designed_events(locus.ref_tag, locus.alt_tag, gap_band)) + designed = Counter(_designed_events(locus.ref_tag, locus.alt_tag, gap_band) if designed is None else designed) residual = [] for event in events: if designed[event]: @@ -3105,6 +4084,8 @@ def marker_type_label(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFA else: residual.append(event) events = residual + if any(event[0] == "unresolved" for event in events): + return "unresolved" kinds = {event[0] for event in events if event[0] in ("snp", "ins", "del")} if not kinds: return "." @@ -3113,22 +4094,81 @@ def marker_type_label(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFA return "both" if "snp" in kinds else "indel" -def _describe(ref: str, sequence: str, gap_band: int, gapped: bool): +def _describe( + ref: str, sequence: str, gap_band: int, gapped: bool, whole: bool = False, unresolved: Optional[Tuple[int, int]] = None, + against: Optional[str] = None, alignment=None, +): """Events of ``sequence`` against ``ref`` (the core of variant_events). ``gapped`` is the caller's decision — row_reading for an observed row, the unguarded cheapest reading for a design — so the description never - re-decides what classification decided.""" - if sequence == ref or len(sequence) != len(ref): + re-decides what classification decided. ``against`` is part of that + decision: the Alt tag, in the frame and at the length of ``ref``, for a + row that was read from it (_read_from_alt). The row is then aligned to + that tag and the events are written against ``ref`` column by column, + so the gaps stand where the row's category was read and the designed + substitution is listed. The row's own alignment to ``ref`` has no + reason to put the Alt base on the target: it can split one gap in two, + or delete the target, to avoid a substitution there. + + A sequence of another length than ``ref`` (a row whose primers were + removed, see trim_locus_rows) is always aligned: the lengths themselves + show a gap. ``whole`` is also the caller's knowledge: the sequence and + ``ref`` both end at the same place (each was cut at its right primer), + so the alignment is anchored at both ends and a difference at the end + is an insertion or a deletion, not ``clip`` or ``overhang``. It is + never inferred from the lengths, which cannot tell a row cut at its + primer from one an insertion pushed the primer out of. When the + lengths differ by more than ``gap_band`` no alignment is attempted: the + shared length is compared base by base and the rest is ``clip`` or + ``overhang``. + + ``unresolved`` is row_decision's ``(ref_index, row_index)`` in the frame + of these two sequences. The part before it is described end to end + (both readings of the row agree on it), and one closing ``unresolved`` + event holds the Ref bases not read and the row's bases that stand + there. + + ``alignment`` is an alignment of these two sequences that the caller + already has (``ops``, ``end_read``, ``end_ref`` as gapped_alignment + gives them). It is written as it stands and none is made here: a row + that read continuation settled was read on more bases than it holds.""" + if alignment is not None: + return _alignment_events(*alignment, ref, sequence) + if against is not None and len(against) != len(ref): + against = None + if unresolved is not None: + first, start = unresolved + if first and not start: # nothing of the row before it: the Ref bases before it are deleted + events = [("del", 1, ref[:first], ".")] + else: + events = _describe( + ref[:first], sequence[:start], gap_band, gapped or first != start, whole=True, + against=None if against is None else against[:first], + ) + events.append(("unresolved", first + 1, ref[first:], sequence[start:])) + return events + if sequence == ref: return [] - if gapped: - ops, end_read, end_ref, _ = gapped_alignment(sequence, ref, gap_band) - else: - return [ + difference = abs(len(sequence) - len(ref)) + if difference > gap_band or not (gapped or difference): + shared = min(len(sequence), len(ref)) + events = [ ("snp", index + 1, ref[index], sequence[index]) - for index in range(len(ref)) + for index in range(shared) if not _design_matches(sequence[index], ref[index]) ] + if shared < len(ref): + events.append(("clip", shared + 1, ref[shared:], ".")) + if shared < len(sequence): + events.append(("overhang", len(ref) + 1, ".", sequence[shared:])) + return events + ops, end_read, end_ref, _ = gapped_alignment(sequence, ref if against is None else against, gap_band, whole) + return _alignment_events(ops, end_read, end_ref, ref, sequence) + + +def _alignment_events(ops, end_read: int, end_ref: int, ref: str, sequence: str): + """The events of one alignment of ``sequence``, written against ``ref`` (see _describe and gapped_alignment).""" ops = _left_align(ops, sequence, ref) events = [] k = 0 @@ -3142,19 +4182,21 @@ def _describe(ref: str, sequence: str, gap_band: int, gapped: bool): run_end = k while run_end + 1 < len(ops) and ops[run_end + 1][0] == kind: run_end += 1 - if kind == "I": - inserted = sequence[i : ops[run_end][1] + 1] - if j > 0: - events.append(("ins", j, ref[j - 1], ref[j - 1] + inserted)) - else: - events.append(("ins", 1, ref[0], inserted + ref[0])) + inserted = sequence[i : ops[run_end][1] + 1] if kind == "I" else "" + deleted = ref[j : ops[run_end][2] + 1] if kind == "D" else "" + name = "ins" if kind == "I" else "del" + before = ops[k - 1] if k else None + if before is not None and before[0] == "M" and _design_matches(sequence[before[1]], ref[before[2]]): + events.append((name, j, ref[j - 1] + deleted, ref[j - 1] + inserted)) else: - deleted = ref[j : ops[run_end][2] + 1] - if j > 0: - events.append(("del", j, ref[j - 1] + deleted, ref[j - 1])) - else: - following = ops[run_end][2] + 1 - events.append(("del", 1, deleted + ref[following], ref[following])) + # The base before the gap cannot anchor it: there is none (a gap + # on the very first base), or the row shows another base there and + # a substitution already uses it (a gap right after the Alt base of + # a row read from the Alt tag). The gap is then written without an + # anchor, from its own first base: 1:.>GG inserts GG before base 1, + # 32:CACG>. deletes bases 32 to 35. Anchoring it on that base would + # use the base twice, and the row could not be rebuilt in order. + events.append((name, j + 1, deleted or ".", inserted or ".")) k = run_end + 1 if end_ref < len(ref): events.append(("clip", end_ref + 1, ref[end_ref:], ".")) @@ -3169,7 +4211,19 @@ def _designed_events(ref: str, alt: str, gap_band: int): return tuple(_describe(ref, alt, gap_band, gapped=_reading(alt, ref, gap_band, guard=False) is not None)) -def variant_events(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT): +def _read_through_gaps( + locus: Locus, sequence: str, gap_band: int, continuations: Optional[Mapping[str, str]] = None +) -> bool: + """Whether a row is described through gaps: every row of a marker whose + own design is an indel, and otherwise a row with an accepted gapped + reading (row_reading, the decision classification made).""" + designed = _designed_events(locus.ref_tag, locus.alt_tag, gap_band) + return any(kind in ("ins", "del") for kind, *_ in designed) or row_reading(locus, sequence, gap_band, continuations) is not None + + +def variant_events( + locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT, continuations: Optional[Mapping[str, str]] = None +): """Every event a row carries against the Ref tag, in 1-based tag coordinates. Returns ``(kind, position, ref_allele, alt_allele)`` tuples in tag order: @@ -3185,19 +4239,108 @@ def variant_events(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT substitutions). Positions are on the tag as printed (design strand); a consumer that knows the strand flips them, as it does for substitutions already. + + A row whose end is unresolved (row_decision) lists its events up to + there and closes with ``unresolved``: the first Ref position not read, + the Ref bases from it on, and the row's own bases that stand there. + + A row read from the Alt tag (_read_from_alt) is aligned to that tag and + written in the Ref tag's positions, so its Variants and its category + show the same base on the target. A gap right after a substituted base + is written without an anchor base (``32:CACG>.``, ``32:.>GG``), as a + gap on the first base of the tag is. + + A row that read continuation settled (row_decision with + ``continuations``) is written from that reading, cut to the row's own + bases. Its alignment was made on more bases than the row holds, so it + is taken from the decision and not made again on the tag. """ - designed = _designed_events(locus.ref_tag, locus.alt_tag, gap_band) - force_gapped = any(kind in ("ins", "del") for kind, *_ in designed) - gapped = force_gapped or row_reading(locus, sequence, gap_band) is not None - return _describe(locus.ref_tag, sequence, gap_band, gapped) + reading, unresolved = row_decision(locus, sequence, gap_band, continuations) + from_alt = _read_from_alt(locus, sequence, gap_band, continuations) + if reading is not None and unresolved is None and (from_alt or reading.template == locus.ref_tag): + return _alignment_events(reading.ops, reading.end_read, reading.end_ref, locus.ref_tag, sequence) + return _describe( + locus.ref_tag, sequence, gap_band, _read_through_gaps(locus, sequence, gap_band, continuations), + unresolved=unresolved_end(locus, sequence, gap_band, continuations), + against=locus.alt_tag if from_alt else None, + ) + + +def _read_from_alt( + locus: Locus, sequence: str, gap_band: int, continuations: Optional[Mapping[str, str]] = None +) -> bool: + """Whether a row's accepted gapped reading was made against the Alt tag. + + row_decision reads a row from the Ref tag or from the Alt tag, whichever + explains it most cheaply; the two tags have the same positions, so the + reading can be written against the Ref tag column by column (_describe). + Never on a marker whose own design is an indel: there the tags' positions + differ past the designed gap, and every row is described by its alignment + to the Ref tag (_read_through_gaps).""" + reading = row_reading(locus, sequence, gap_band, continuations) + if reading is None or reading.template != locus.alt_tag or locus.alt_tag == locus.ref_tag: + return False + return not any(kind in ("ins", "del") for kind, *_ in _designed_events(locus.ref_tag, locus.alt_tag, gap_band)) + + +def unresolved_end( + locus: Locus, sequence: str, gap_band: int, continuations: Optional[Mapping[str, str]] = None +) -> Optional[Tuple[int, int]]: + """row_decision's unresolved stretch in the Ref tag's coordinates, as a row's Variants show it, or None. + + The decision counts positions on the canonical tag each reading was + made against. Those are the Ref tag's positions, except on a marker + whose own design is an indel, for a reading against the Alt tag past + the designed indel. There the stretch is placed by the base of the row + it starts at, which is the same in every frame: the Ref position is the + one the row's alignment to the Ref tag (the one its Variants are + written from, _read_through_gaps) puts under that base, moved back over + any Ref bases deleted right before it. A known designed indel does not + settle another gap near the row's end.""" + stretch = row_decision(locus, sequence, gap_band, continuations).unresolved + if stretch is None or stretch[0] <= locus.variant_pos: + return stretch + if not any(kind in ("ins", "del") for kind, *_ in _designed_events(locus.ref_tag, locus.alt_tag, gap_band)): + return stretch + start = stretch[1] + ops = _left_align(gapped_alignment(sequence, locus.ref_tag, gap_band)[0], sequence, locus.ref_tag) + at = next((k for k, (kind, i, _) in enumerate(ops) if kind != "D" and i >= start), None) + if at is None: + return None # the row's unread bases lie past the Ref tag's end: no Ref position stands for them + first = ops[at][2] + while at > 0 and ops[at - 1][0] == "D": + at -= 1 + first = ops[at][2] + if first >= len(locus.ref_tag) or abs(first - start) > gap_band: + return None + return first, start + + +def events_either_way(ref: str, sequence: str, gap_band: int): + """Events of a sequence of another length than ``ref`` when they are the + same whether or not the two end at the same place, otherwise ``None``. + + For a consumer of a table without primers that has no Variants to read: + the sequences do not say whether a row was cut at its right primer + (``whole`` in _describe). Where both readings agree the question does + not matter, an indel well inside the row; where they differ, or the + lengths differ by more than ``gap_band``, the row cannot be read. + """ + if abs(len(sequence) - len(ref)) > gap_band: + return None + events = _describe(ref, sequence, gap_band, True) + return events if events == _describe(ref, sequence, gap_band, True, whole=True) else None def format_variants(events) -> str: - """The Variants cell: ``;``-joined tokens, ``pos:REF>ALT`` per event plus ``clip=k`` / ``overhang=k``; '.' when empty.""" + """The Variants cell: ``;``-joined tokens, ``pos:REF>ALT`` per event plus ``clip=k`` / ``overhang=k`` / + ``unresolved=k`` (the last ``k`` Ref bases are not read in this row); '.' when empty.""" tokens = [] for kind, position, ref_allele, alt_allele in events: if kind == "clip": tokens.append(f"clip={len(ref_allele)}") + elif kind == "unresolved": + tokens.append(f"unresolved={len(ref_allele)}") elif kind == "overhang": tokens.append(f"overhang={len(alt_allele)}") else: @@ -3205,7 +4348,69 @@ def format_variants(events) -> str: return ";".join(tokens) or "." -def classify_sequence(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT) -> str: +def parse_variants(text: str, ref: str, sequence: str): + """The events a Variants cell holds: the inverse of format_variants. + + ``ref`` and ``sequence`` (the Ref tag and the row, as printed) restore + what the ``clip`` and ``overhang`` tokens leave out. Lets a consumer + of the table take a row's reading from it and not derive its own, + which matters for a table written without primers: only ``generate`` + knows which rows end at their right primer. A token this version does + not know raises ValueError: the cell then says something about the row + that cannot be read here, and must not be replaced by a guess. + """ + events = [] + for token in text.split(";"): + if token in ("", "."): + continue + if token.startswith("unresolved="): + # The row's bases that stand there are what the tokens before it leave over. + first = len(ref) - int(token[11:]) + shift = sum( + len(added.strip(".")) - len(removed.strip(".")) + for kind, _, removed, added in events + if kind in ("ins", "del") + ) + if first < 0 or not 0 <= first + shift <= len(sequence): + raise ValueError(f"Variants token {token!r} does not fit the row") + events.append(("unresolved", first + 1, ref[first:], sequence[first + shift :])) + elif token.startswith("clip="): + clipped = int(token[5:]) + events.append(("clip", len(ref) - clipped + 1, ref[len(ref) - clipped :], ".")) + elif token.startswith("overhang="): + events.append(("overhang", len(ref) + 1, ".", sequence[len(sequence) - int(token[9:]) :])) + else: + position, alleles = token.split(":", 1) + ref_allele, alt_allele = alleles.split(">", 1) + removed, added = len(ref_allele.strip(".")), len(alt_allele.strip(".")) + kind = "snp" if removed == added == 1 else ("ins" if added > removed else "del") + events.append((kind, int(position), ref_allele, alt_allele)) + return events + + +def category_base( + locus: Locus, sequence: str, gap_band: int, continuations: Optional[Mapping[str, str]] = None +) -> Optional[int]: + """Which base of a row its category is read from, as an index into the row; None when it shows none. + + The fixed offset, or where the row's accepted gapped reading puts the + target (row_decision). None for a target inside a deletion, past the + row's end, or in an unresolved end. classify_sequence names the + category from this base and right_primer_cut never removes it. + """ + decision = row_decision(locus, sequence, gap_band, continuations) + if _target_unread(locus, decision): + return None + if decision.reading is None: + index = locus.variant_pos + else: + index = decision.reading.ref_to_read.get(locus.variant_pos) + return index if index is not None and index < len(sequence) else None + + +def classify_sequence( + locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFAULT, continuations: Optional[Mapping[str, str]] = None +) -> str: """Classify an observed tag against the canonical Ref/Alt definitions. The Ref/Alt categories require exact sequence equality; per-row read @@ -3219,26 +4424,22 @@ def classify_sequence(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFA clustered errors at the read end must not masquerade as a shift). That reading is the same one variant_events describes, so a row's category and its Variants never disagree about where the target sits. A target inside a deletion, or - pushed past the read, is missing data and classifies as Other. The + pushed past the read, is missing data and classifies as Other. So does + a target in the unresolved end of a row (row_decision): a gapped reading + is cheaper there but unverified, the two readings can put different + bases at the target, and neither is taken. The variant-base comparison is IUPAC-aware on the design side only: an ambiguous observed base such as N is missing data, not evidence for - either allele, and classifies as Other. + either allele, and classifies as Other. ``continuations`` are handed + to row_decision, which may settle an unresolved end with them. """ if sequence == locus.ref_tag: return "Ref" if sequence == locus.alt_tag: return "Alt" - index = locus.variant_pos - if gap_band > 0: - # The cheapest substitution-only reading over both canonicals is the - # bound a gapped reading must beat; the reading itself is the one - # accepted_gapped_reading gives, shared with the row's Variants. - best = row_reading(locus, sequence, gap_band) - if best is not None: - mapped = best.ref_to_read.get(locus.variant_pos) - if mapped is None or mapped >= len(sequence): - return "Other" - index = mapped + index = category_base(locus, sequence, gap_band, continuations) + if index is None: + return "Other" base = sequence[index] if len(IUPAC_BASES.get(base, frozenset(base))) != 1: return "Other" @@ -3249,6 +4450,391 @@ def classify_sequence(locus: Locus, sequence: str, gap_band: int = GAP_BAND_DEFA return "Other" +# ---------------------------------------------------------------------------- +# Primer removal (--remove-primers): the same rows, shown without their primers +# ---------------------------------------------------------------------------- + +TRIM_MIN_BASES = 10 # a row keeps its right primer when fewer of its own bases than this would remain +PRIMER_TAIL_MIN = 8 # bases of a right primer's start that identify it at the end of a row, on a marker with a site +PRIMER_TAIL_UNLOCATED = 10 # ... on a marker without one, where 8 bases match by chance (8 in 100,000 rows; none at 10) +AMPLICON_MIN_OVERLAP = 6 # bases a tag's end must share with the start of its right primer to vote on the amplicon length +AMPLICON_MIN_MARKERS = 20 # such votes a panel needs before its amplicon length is used +AMPLICON_MAX_CLASH = 0.05 # share of the overlapping tags that may contradict the amplicon length +PRIMER_REMOVAL_TALLIES = ( # counted by trim_locus_rows, reported in the QC file + "rows_merged", + "rows_merged_across_allele_groups", + "rows_right_primer_removed", + "rows_right_primer_kept_target", + "rows_right_primer_kept_short", + "rows_right_primer_kept_collision", + "markers_right_primer_kept", +) + + +def amplicon_geometry(loci: Sequence[Locus]) -> Optional[Tuple[int, bool]]: + """The panel's amplicon length and whether its right primers are listed reverse-complemented, or ``None``. + + On a platform with one amplicon length (DArTag) every right primer + starts ``amplicon length - primer length`` bases from the tag start, so + the tags that run into their own primer agree on one length. Each + candidate length is scored by the tags whose end reads as the start of + their primer over AMPLICON_MIN_OVERLAP bases or more, less three for + each tag that contradicts it. ``None`` when fewer than + AMPLICON_MIN_MARKERS tags support the best length or more than + AMPLICON_MAX_CLASH of the overlapping tags contradict it: the panel has + no single amplicon length, or its tags never reach the right primer. + """ + with_primer = [locus for locus in loci if locus.right_primer] + if not with_primer: + return None + tag = len(with_primer[0].ref_tag) + best = None + for reverse in (False, True): + primers = [reverse_complement(locus.right_primer) if reverse else locus.right_primer for locus in with_primer] + for length in range(tag - 10, tag + 60): + agree = strong = clash = 0 + for locus, primer in zip(with_primer, primers): + overlap = len(locus.ref_tag) - (length - len(primer)) + if not 0 < overlap <= len(primer): + continue + if compatible_mismatches(locus.ref_tag[-overlap:], primer[:overlap], 0) == 0: + agree += 1 + strong += overlap >= AMPLICON_MIN_OVERLAP + else: + clash += 1 + if best is None or strong - 3 * clash > best[0]: + best = (strong - 3 * clash, strong, agree, clash, length, reverse) + _, strong, agree, clash, length, reverse = best + if strong < AMPLICON_MIN_MARKERS or clash > AMPLICON_MAX_CLASH * max(1, agree + clash): + return None + return length, reverse + + +def right_primer_site(locus: Locus, geometry: Optional[Tuple[int, bool]]) -> Tuple[Optional[Tuple[int, str]], str]: + """Where a marker's right primer starts on its Ref tag: ``((start, primer), "located")`` or ``(None, reason)``. + + ``primer`` is the right primer as the tag reads it. ``start`` may lie + past the end of the tag: the Ref tag then holds no primer base, but a + deletion can still bring the primer into a row. With a panel amplicon + length the primer starts where that length puts it. A whole copy of + the primer elsewhere in the tag is then part of the insert, unless the + tag does not read as the primer at that place: such a marker has an + amplicon of another length, and its primer is the copy. Without a + panel amplicon length (``geometry`` is None) only a primer that lies + whole inside the Ref tag is located. A marker whose target would fall + inside the primer, or whose tag contradicts the amplicon length and + holds no whole primer, is not located: its rows are cut on the right + only where right_primer_cut finds the primer itself. + """ + if not locus.right_primer: + return None, "no_right_primer" + after_left = len(locus.left_primer) + if geometry is None: + hits = [ + (_find_primer(locus.ref_tag, primer, after_left), primer) + for primer in (locus.right_primer, reverse_complement(locus.right_primer)) + ] + hits = [hit for hit in hits if hit[0] > locus.variant_pos] + return (min(hits), "located") if hits else (None, "no_amplicon_length") + length, reverse = geometry + primer = reverse_complement(locus.right_primer) if reverse else locus.right_primer + start = length - len(primer) + shown = locus.ref_tag[start : start + len(primer)] # the tag's bases at that place; none when it lies past the tag + agrees = compatible_mismatches(shown, primer[: len(shown)], 0) == 0 + if not agrees: + inside = _find_primer(locus.ref_tag, primer, after_left) + if inside >= 0: + start, agrees = inside, True + if start <= locus.variant_pos: + return None, "target_in_right_primer" + if not agrees: + return None, "disagrees_with_amplicon_length" + return (start, primer), "located" + + +def _cheapest_ops(row: str, template: str, gap_band: int, slack: Sequence[int] = (0,)): + """How ``row`` reads along ``template``: base by base, unless a gapped alignment costs strictly less. + + ``slack`` lists how many template bases beyond the row's length each + alignment may use: none leaves room for a net insertion, ``gap_band`` + for a net deletion. Cost is (edits, gap bases); gaps are left-aligned. + """ + width = min(len(row), len(template)) + best = (tag_mismatches(row[:width], template[:width]), 0, tuple(("M", index, index) for index in range(width))) + if gap_band > 0: + for extra in slack: + target = template[: len(row) + extra] + ops, _, _, edits = gapped_alignment(row, target, gap_band) + gaps = sum(1 for kind, _, _ in ops if kind != "M") + if gaps and (edits, gaps) < best[:2]: + best = (edits, gaps, tuple(_left_align(ops, row, target))) + return best[2] + + +def right_primer_cut( + locus: Locus, sequence: str, site: Optional[Tuple[int, str]], gap_band: int, + continuations: Optional[Mapping[str, str]] = None, +) -> Tuple[int, Optional[str]]: + """How many bases after a row's left primer are the sample's own: ``(cut, kept)``. + + The row without its primers is ``sequence[len(left primer):][:cut]``. + ``kept`` is None, or why a right primer found in the row stays in it: + "target" (the cut would remove the base the row's category was read + from) or "short" (fewer than TRIM_MIN_BASES bases would remain). + + A row is a fixed-length window of its amplicon, so an insertion moves + the right primer toward the row's end and a deletion brings more of it + in. With ``site`` (right_primer_site) the row is read along "the Ref + tag up to the primer, then the primer", and the cut is where that + reading reaches the primer. An indel in the last bases before the + primer costs no less than substitutions there, so the reading misses + it. Two rules read such an end from the primer instead. A deletion: + the row reads exactly as primer from 2 to ``gap_band`` bases earlier, + and the reading leaves two or more bases from there on unexplained. + An insertion: the bases at the cut are not the primer's (two or more + differ), and the row reads exactly as primer from up to ``gap_band`` + bases later. + + Last, the primer is looked for directly, in a row whose cut does not + read as primer and in every row of a marker without a site: whole, or + as an exact start of PRIMER_TAIL_MIN bases or more that ends the row + (PRIMER_TAIL_UNLOCATED without a site, where nothing says the primer is + near and either strand is tried). That finds products shorter than + ``gap_band`` allows for. The whole primer is not looked for on a + marker whose own Ref tag holds a copy of it before the site: there a + copy in a row is the insert's, not the end of a shorter product. + + No cut removes the base the row's category was read from + (category_base). The alignment made here to find the primer can put + the target elsewhere, so it is not asked. A row whose target is not + read has no such base, and is cut wherever its primer is found. + """ + after_left = len(locus.left_primer) + body = sequence[after_left:] + size = len(body) + cut = size + read_from = category_base(locus, sequence, gap_band, continuations) + + def primer_from(index: int, primer: str) -> bool: + """body[index:] is exactly the start of ``primer``.""" + return size - index <= len(primer) and tag_mismatches(body[index:], primer[: size - index]) == 0 + + def removes_category_base(index: int) -> bool: + """A cut at ``index`` takes the base the row's category was read from.""" + return read_from is not None and index <= read_from - after_left + + primers: Tuple[str, ...] = () + if site is not None: + start, primer = site + primers = (primer,) + ref_part = locus.ref_tag[after_left : min(start, len(locus.ref_tag))] + template = ref_part + "N" * (start - after_left - len(ref_part)) + primer + template += "N" * max(0, size + gap_band - len(template)) # what follows the primer is unknown + ops = _cheapest_ops(body, template, gap_band, (0, gap_band)) + inserted = sum(1 for kind, _, j in ops if kind == "I" and j <= start - after_left) + deleted = sum(1 for kind, _, j in ops if kind == "D" and j < start - after_left) + cut = min(max(start - after_left + inserted - deleted, 0), size) + aligned = {i: j for kind, i, j in ops if kind == "M"} + moved = False + for shift in range(2, min(gap_band, cut - TRIM_MIN_BASES) + 1): + earlier = cut - shift + if primer_from(earlier, primer) and 2 <= sum( + 1 for i in range(earlier, size) if i not in aligned or not _design_matches(body[i], template[aligned[i]]) + ): + if not removes_category_base(earlier): + cut, moved = earlier, True + break + at_cut = body[cut : cut + len(primer)] + if not moved and size - cut >= 2 and tag_mismatches(at_cut, primer[: len(at_cut)]) >= 2: + for shift in range(1, gap_band + 1): + later = cut + shift + if later > size - 2: + break + if primer_from(later, primer): + cut = later + break + elif locus.right_primer: + primers = (locus.right_primer, reverse_complement(locus.right_primer)) + if not (site is not None and cut < size and primer_from(cut, primers[0])): + repeated = site is not None and 0 <= _find_primer(locus.ref_tag, site[1], after_left) < site[0] + for primer in primers: + hit = -1 if repeated else _find_primer(body, primer, 1) + if hit < 0: + least = PRIMER_TAIL_MIN if site is not None else PRIMER_TAIL_UNLOCATED + tails = range(1, min(cut, size - least + 1)) + hit = next((index for index in tails if primer_from(index, primer)), -1) + if 0 < hit < cut: + cut = hit + break + if cut < size: + if removes_category_base(cut): + return size, "target" + if cut < TRIM_MIN_BASES: + return size, "short" + return cut, None + + +def trim_locus_rows( + locus: Locus, + rows: Sequence[Tuple[int, str, str]], + counts: Mapping[str, Sequence[int]], + site: Optional[Tuple[int, str]], + 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 + fixed length (the read pass admits no indel in it); the right one is + cut where right_primer_cut finds it. Rows that become the same + sequence are one row with their reads added. Rows of two allele groups + that would become the same sequence keep their right end instead and + stay separate (tallied as a collision), so the reads behind each allele + of the target are those of the untrimmed table. The + returned locus is the marker in the trimmed frame: its Ref and Alt rows + as its tags, the target counted from the first base after the left + primer, so the row annotations are computed against the Ref row as + printed. + + ``readings`` gives ``_describe`` what the trimmed sequences no longer + show, as ``(gapped, whole, unresolved, against, alignment)`` per row + (``against``: the Alt row as printed when the category was read from + the Alt tag, so the row is described from the same reading; + ``alignment``: for a row that read continuation settled, the alignment + it was read from, cut to the bases shown). ``gapped`` is the + decision made on the full tag (_read_through_gaps): a primer that + verified a gap is gone from the row, so the decision is carried, not + made again. ``whole`` marks a row that was cut at its right primer on + a marker whose Ref row ends at its own: the two are compared end to + end, every other row as a fixed-length window. ``unresolved`` is the + stretch the full tag's decision left unread (unresolved_end), counted in + the trimmed frame, and it is carried whatever length the row was cut + to: a row that is Other because its target was not read never shows a + reading of that target. It is None only when the whole row is read, or + when the stretch lay in the primer that was cut from the Ref row. + """ + after_left = len(locus.left_primer) + cuts = {sequence: right_primer_cut(locus, sequence, site, gap_band, continuations) for _, _, sequence in rows} + without_primers = lambda sequence: sequence[after_left : after_left + cuts[sequence][0]] + if without_primers(locus.ref_tag) == without_primers(locus.alt_tag): + # right_primer_cut keeps the target base, so the canonical rows stay + # distinct; if they ever would not, the marker keeps its right end. + cuts = {sequence: (len(sequence) - after_left, None) for sequence in cuts} + tally["markers_right_primer_kept"] += 1 + else: + # Keep colliding rows from different allele groups apart by retaining + # their right primer, so no read ever moves between allele groups. + by_trimmed: Dict[str, List[Tuple[str, str]]] = defaultdict(list) + for _, category, sequence in rows: + by_trimmed[without_primers(sequence)].append((category, sequence)) + for members in by_trimmed.values(): + if len({ALLELE_GROUP[cat] for cat, _ in members}) > 1: + has_canonical = any(cat in ("Ref", "Alt") for cat, _ in members) + for cat, seq in members: + if has_canonical and cat in ("Ref", "Alt"): + continue + if cuts[seq][0] < len(seq) - after_left: + cuts[seq] = (len(seq) - after_left, "collision") + def settled_alignment(sequence: str): + """The alignment read continuation settled a row with, among the bases shown; None for any other row.""" + reading, unresolved = row_decision(locus, sequence, gap_band, continuations) + if reading is None or unresolved is not None or row_decision(locus, sequence, gap_band).unresolved is None: + return None + if reading.template != locus.ref_tag and not _read_from_alt(locus, sequence, gap_band, continuations): + return None # read from the Alt tag of a designed indel: not in the Ref tag's positions + if any(kind != "M" for kind, i, j in reading.ops if i < after_left or j < after_left): + return None # a gap in the left primer: the row and the Ref row as shown start at different bases + return _cut_alignment(reading.ops, after_left, cuts[sequence][0], cuts[locus.ref_tag][0]) + + groups: Dict[str, List[Tuple[str, str, int]]] = defaultdict(list) + summed_counts: Dict[str, List[int]] = {} + for _, category, sequence in rows: + trimmed = without_primers(sequence) + reads = counts[sequence] + total = sum(reads) + 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) + else: + summed_counts[trimmed] = [kept + added for kept, added in zip(summed_counts[trimmed], reads)] + merged_category: Dict[str, str] = {} + winner_of: Dict[str, str] = {} + for trimmed, members in groups.items(): + canonical = next(((cat, seq) for cat, seq, _ in members if cat in ("Ref", "Alt")), None) + if canonical is not None: + win_cat, win_seq = canonical + else: + by_cat: Counter = Counter() + deepest: Dict[str, Tuple[int, str]] = {} + for cat, seq, total in members: + by_cat[cat] += total + if cat not in deepest or total > deepest[cat][0]: + deepest[cat] = (total, seq) + win_cat = max(by_cat, key=lambda cat: (by_cat[cat], -ALLELE_TYPE_ORDER.get(cat, 99))) + win_seq = deepest[win_cat][1] + merged_category[trimmed] = win_cat + winner_of[trimmed] = win_seq + if len(members) > 1: + tally["rows_merged"] += len(members) - 1 + tally["rows_merged_across_allele_groups"] += sum( + ALLELE_GROUP[cat] != ALLELE_GROUP[win_cat] for cat, _, _ in members + ) + shown = dataclasses.replace( + locus, + left_primer="", + right_primer="", + variant_pos=locus.variant_pos - after_left, + ref_tag=without_primers(locus.ref_tag), + alt_tag=without_primers(locus.alt_tag), + ) + trimmed_rows = [ + (ALLELE_TYPE_ORDER.get(category, 99), category, sequence) for sequence, category in merged_category.items() + ] + trimmed_rows.sort(key=lambda row: (row[0], row[2])) + uncut = len(locus.ref_tag) - after_left + # The Ref row ends at its primer when it was cut, or when the primer starts exactly where the tag ends. + ref_ends_at_primer = len(shown.ref_tag) < uncut or (site is not None and site[0] == len(locus.ref_tag)) + # Every reading attribute (gapped, unresolved, against, settled) follows the + # winning source row so low-count error rows trimmed into a clean or canonical + # row cannot poison its Variants or MarkerType. + readings = {} + for trimmed, winner in winner_of.items(): + stretch = unresolved_end(locus, winner, gap_band, continuations) + trimmed_unresolved: Optional[Tuple[int, int]] = None + if stretch is not None: + first, start = max(stretch[0] - after_left, 0), max(stretch[1] - after_left, 0) + # A row cut before the stretch begins lost bases both readings agree + # on; the Ref bases that stood for them are not read either. + cut_short = start - len(trimmed) + if cut_short > 0: + first, start = max(first - cut_short, 0), len(trimmed) + if first < len(shown.ref_tag): + trimmed_unresolved = (first, start) + readings[trimmed] = ( + _read_through_gaps(locus, winner, gap_band, continuations), + ref_ends_at_primer and len(trimmed) < uncut, + trimmed_unresolved, + shown.alt_tag if _read_from_alt(locus, winner, gap_band, continuations) else None, + settled_alignment(winner), + ) + return shown, trimmed_rows, summed_counts, readings + + # ============================================================================ # 8. MADC input/output and QC # ============================================================================ @@ -3289,30 +4875,117 @@ def build_dart_preamble( ] +def is_madc_header(row: Sequence[str]) -> bool: + """The header row names AlleleID: first in vendor and MADCATS files, after + a leading Code_version column in HapApp's fixed-allele-ID output.""" + return any(cell.strip() == "AlleleID" for cell in row) + + def find_madc_header(rows: Sequence[Sequence[str]]) -> int: for index, row in enumerate(rows): - if row and row[0].strip() == "AlleleID": + if is_madc_header(row): return index raise MadcError("Could not find an AlleleID header row in MADC file") -def read_madc(path: Path): - with open_text(path, "rt") as handle: - rows = list(csv.reader(handle)) - header_index = find_madc_header(rows) - header = rows[header_index] +def madc_identity_columns(header: Sequence[str], path: Path) -> Tuple[int, int, int]: + """Indices of AlleleID, CloneID and AlleleSequence in a MADC header row.""" try: - allele_index = header.index("AlleleID") - clone_index = header.index("CloneID") - sequence_index = header.index("AlleleSequence") + return header.index("AlleleID"), header.index("CloneID"), header.index("AlleleSequence") except ValueError as exc: raise MadcError(f"MADC is missing a required identifier column: {path}") from exc + + +# Processed MADCs can carry a per-row read total between the sequence columns and the samples. +READ_TOTAL_COLUMN = "readCountSum" + + +def madc_sample_start(header: Sequence[str]) -> int: + """First per-sample column: after the statistics block, or after the sequence columns of a + short layout, and after the per-row read total where there is one.""" if "RatioAvgCountRefAvgCountSnp" in header: - sample_start = header.index("RatioAvgCountRefAvgCountSnp") + 1 + start = header.index("RatioAvgCountRefAvgCountSnp") + 1 elif "ClusterConsensusSequence" in header: - sample_start = header.index("ClusterConsensusSequence") + 1 + start = header.index("ClusterConsensusSequence") + 1 else: - sample_start = sequence_index + 1 + start = header.index("AlleleSequence") + 1 + if [cell.strip() for cell in header[start : start + 1]] == [READ_TOTAL_COLUMN]: + start += 1 + return start + + +def madc_read_counts(cells: Sequence[str], path: Path) -> List[int]: + """A MADC row's per-sample counts. Blank cells are 0; HapApp writes counts of merged rows as floats (12.0).""" + try: + return list(map(int, cells)) + except ValueError: + counts = [] + for value in cells: + try: + counts.append(int(float(value or 0))) + except ValueError as exc: + raise MadcError(f"Non-numeric read count {value!r} in {path}") from exc + return counts + + +class CountOverflowCheck: + """Signed 8-bit overflow in a MADC's counts. + + Some vendor MADCs store counts in a signed byte: counts of 128-255 come + out as count - 256 (negative) and counts of 256 or more wrap to small + positives with no trace. A negative read count is impossible, so any is + reported, and a maximum of exactly 127 beside negatives points to overflow. + Adding 256 to the negatives would recover only the 128-255 band, so the + counts are reported, never corrected. + """ + + def __init__(self) -> None: + self.negative_cells = 0 + self.markers: Set[str] = set() + self.minimum: Optional[int] = None + self.maximum: Optional[int] = None + + def add(self, clone_id: str, counts: Sequence[int]) -> None: + if not counts: + return + low, high = min(counts), max(counts) + self.minimum = low if self.minimum is None else min(self.minimum, low) + self.maximum = high if self.maximum is None else max(self.maximum, high) + if low < 0: + self.negative_cells += sum(value < 0 for value in counts) + self.markers.add(clone_id) + + def summary(self) -> Dict[str, object]: + return { + "negative_cells": self.negative_cells, + "markers_with_negative_cells": len(self.markers), + "minimum": self.minimum, + "maximum": self.maximum, + "signed_8bit_signature": bool(self.negative_cells) and self.maximum == 127, + } + + def warning(self, path: Path) -> Optional[str]: + if not self.negative_cells: + return None + message = ( + f"warning: {path} has {self.negative_cells:,} negative read counts across {len(self.markers):,} " + f"markers (minimum {self.minimum})" + ) + if self.maximum == 127: + message += ( + ", and its largest count is exactly 127: the counts look like signed 8-bit overflow, where " + "128-255 are stored as count - 256 and counts of 256 or more wrap silently" + ) + return message + ". Counts are used as stored; regenerate them from the FASTQs or ask the vendor." + + +def read_madc(path: Path): + with open_text(path, "rt") as handle: + rows = list(csv.reader(handle)) + header_index = find_madc_header(rows) + header = rows[header_index] + allele_index, clone_index, sequence_index = madc_identity_columns(header, path) + sample_start = madc_sample_start(header) sample_names = list(header[sample_start:]) for preamble in reversed(rows[:header_index]): values = [value.strip() for value in preamble[sample_start:]] @@ -3327,16 +5000,13 @@ def read_madc(path: Path): sample_names = values break records = [] + overflow = CountOverflowCheck() for row in rows[header_index + 1 :]: if not row or not row[allele_index].strip(): continue padded = list(row) + [""] * max(0, len(header) - len(row)) - counts = [] - for value in padded[sample_start : sample_start + len(sample_names)]: - try: - counts.append(int(float(value or 0))) - except ValueError as exc: - raise MadcError(f"Non-numeric read count {value!r} in {path}") from exc + counts = madc_read_counts(padded[sample_start : sample_start + len(sample_names)], path) + overflow.add(padded[clone_index], counts) records.append( { "allele_id": padded[allele_index], @@ -3345,7 +5015,12 @@ def read_madc(path: Path): "counts": counts, } ) - return {"samples": sample_names, "records": records, "header_index": header_index} + warning = overflow.warning(path) + if warning: + print(warning, file=sys.stderr) + return { + "samples": sample_names, "records": records, "header_index": header_index, "count_overflow": overflow.summary() + } def allele_type(allele_id: str) -> str: @@ -3381,6 +5056,15 @@ def write_madc( '.' rather than blank. Reads in sequences that pass no route are tallied in the exclusion buckets so the table's coverage of assigned reads is always visible. + + With ``options.remove_primers`` the rows are chosen and classified as + above, then shown without their primers (trim_locus_rows): sequences, + consensus, Variants and MarkerType are those of the trimmed rows, and + rows that become identical are one row. + + What the reads carry after their tags is pooled over the samples first + (pooled_continuations) and handed to every reading of a row, so a row + whose end the tag leaves unresolved can be settled (row_decision). """ output.parent.mkdir(parents=True, exist_ok=True) observed: Dict[int, Counter] = defaultdict(Counter) @@ -3405,6 +5089,14 @@ def write_madc( } reads_in_emitted_rows = 0 per_sample_emitted = [0] * len(results) + unresolved_ends = {"rows": 0, "reads": 0, "rows_target_not_read": 0, "reads_target_not_read": 0} + 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} with output.open("w", newline="") as handle: writer = csv.writer(handle, lineterminator="\n") for row in options.preamble or (): @@ -3415,6 +5107,7 @@ def write_madc( ] writer.writerow(header_columns + [result.sample.display_name for result in results]) for locus in loci: + after_tag = continuations.get(locus.index) forced = {locus.ref_tag: "Ref", locus.alt_tag: "Alt"} sequences = set(forced) for sequence, count in observed.get(locus.index, {}).items(): @@ -3429,22 +5122,50 @@ def write_madc( excluded[route]["reads"] += count rows = [] for sequence in sequences: - category = forced.get(sequence) or classify_sequence(locus, sequence, gap_band) + category = forced.get(sequence) or classify_sequence(locus, sequence, gap_band, after_tag) rows.append((ALLELE_TYPE_ORDER.get(category, 99), category, sequence)) + stretch = row_decision(locus, sequence, gap_band, after_tag).unresolved + reads = observed[locus.index][sequence] + if stretch is not None: + # Counted on the full tags, so the tally is the same with and without primers. + target_in_it = locus.variant_pos >= stretch[0] + unresolved_ends["rows"] += 1 + unresolved_ends["reads"] += reads + unresolved_ends["rows_target_not_read"] += target_in_it + unresolved_ends["reads_target_not_read"] += reads * target_in_it + elif row_decision(locus, sequence, gap_band).unresolved is not None: + read_continuation["rows_settled"] += 1 # its target is unread on the tag alone + read_continuation["reads_settled"] += reads rows.sort(key=lambda row: (row[0], row[2])) + counts_by_sequence = { + 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, + kept_primer, + ) + designed = _describe(locus.ref_tag, locus.alt_tag, gap_band, *readings[locus.alt_tag]) type_serials = Counter() - ref_counts = [result.counts.get((locus.index, locus.ref_tag), 0) for result in results] - alt_counts = [result.counts.get((locus.index, locus.alt_tag), 0) for result in results] + ref_counts = counts_by_sequence[locus.ref_tag] + alt_counts = counts_by_sequence[locus.alt_tag] canonical_call_rate = sum((ref + alt) > 0 for ref, alt in zip(ref_counts, alt_counts)) / len(results) avg_ref = mean_nonzero(ref_counts) avg_alt = mean_nonzero(alt_counts) for _, category, sequence in rows: - counts = [result.counts.get((locus.index, sequence), 0) for result in results] + counts = counts_by_sequence[sequence] type_serials[category] += 1 suffix = category 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) @@ -3463,8 +5184,11 @@ def write_madc( # its MarkerType label; the sidecar gets one line per event. label = variants = "." if options.annotations: - events = variant_events(locus, sequence, gap_band) - label = marker_type_label(locus, sequence, gap_band, events) + if readings is None: + events = variant_events(locus, sequence, gap_band, after_tag) + else: + events = _describe(locus.ref_tag, sequence, gap_band, *readings[sequence]) + label = marker_type_label(locus, sequence, gap_band, events, designed) marker_type_counts[label] += 1 variants = format_variants(events) if events: @@ -3504,7 +5228,19 @@ def write_madc( writer.writerows(sidecar_rows) elif options.variants_path is not None and options.variants_path.exists(): options.variants_path.unlink() # a sidecar from an earlier run must not outlive the table it described + primer_removal = {} + if options.remove_primers: + primer_removal["primer_removal"] = { + "amplicon_length": geometry[0] if geometry else None, + "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, "rows": rows_written, "categories": dict(category_counts), "marker_types": dict(marker_type_counts), @@ -3515,6 +5251,8 @@ def write_madc( }, "novel_rows_by_evidence_route": dict(route_counts), "excluded_novel": excluded, + "unresolved_ends": unresolved_ends, + "read_continuation": read_continuation, "reads_in_emitted_rows": reads_in_emitted_rows, "per_sample_reads_in_emitted_rows": per_sample_emitted, } @@ -3591,6 +5329,7 @@ def validate_madc(generated_path: Path, expected_path: Path) -> Dict[str, object "generated": len(generated_samples), "expected": len(expected_samples), }, + "count_overflow": {"generated": generated["count_overflow"], "expected": expected["count_overflow"]}, "allele_rows": { "common": len(common_rows), "generated": len(generated_rows), @@ -3657,7 +5396,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: @@ -4389,7 +6128,7 @@ def _evidence_rule(args: argparse.Namespace) -> EvidenceRule: ) -def _assignment_settings(args: argparse.Namespace) -> AssignmentSettings: +def _assignment_settings(args: argparse.Namespace, families: Tuple[Tuple[int, ...], ...] = ()) -> AssignmentSettings: """The read-pass settings, which are also the cache key.""" return AssignmentSettings( tag_length=args.tag_length, @@ -4398,9 +6137,42 @@ def _assignment_settings(args: argparse.Namespace) -> AssignmentSettings: partial_min_length=args.min_partial_length, gap_band=args.max_indel_length if args.gapped_rescue == "on" else 0, leading_anchor=(getattr(args, "leading_anchor", None) or "").upper(), + tile_families=families, + leading_anchor_mismatches=args.leading_anchor_mismatches, ) +def _report_tile_families(loci: Sequence[Locus], families: Tuple[Tuple[int, ...], ...], mode: str) -> None: + """Name the tile families on stderr, and the tiles a narrower mode leaves tied.""" + def describe(groups: Sequence[Tuple[int, ...]]) -> str: + shown = ", ".join("+".join(loci[index].marker for index in group) for group in groups[:5]) + return shown + (f" and {len(groups) - 5} more" if len(groups) > 5 else "") + + if families: + declared_of = _declared_locus_groups(loci) + detected = sum( + 1 for family in families + if not declared_of[family[0]] or len({declared_of[index] for index in family}) > 1 + ) + print( + f"generate: {len(families)} tile famil{'y' if len(families) == 1 else 'ies'} " + f"({sum(map(len, families))} markers; {detected} detected, {len(families) - detected} declared by " + f"LocusGroup); a read is credited to every tile it fits: " + f"{describe(families)}", + file=sys.stderr, + ) + if mode != "auto": + linked = {index for family in families for index in family} + missed = [family for family in tile_families(loci, "auto") if not linked.issuperset(family)] + if missed: + print( + f"warning: {sum(map(len, missed))} markers read a tag window shared with another marker but are " + f"not linked with --tile-groups {mode}, so reads that fit them equally are dropped as ambiguous: " + f"{describe(missed)}; declare a LocusGroup or use --tile-groups auto", + file=sys.stderr, + ) + + def _discover_samples(args: argparse.Namespace) -> Tuple[List[Sample], Path, List[Path]]: """The run's samples: one per FASTQ, named from the target manifest or the lookup.""" fastq_directory = Path(args.fastq_dir) @@ -4453,15 +6225,21 @@ def _assign_samples( settings: AssignmentSettings, cache_dir: Optional[str], jobs: int, + cache_gzip_level: int = GZIP_LEVEL_DEFAULT, + 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, cache_gzip_level, keep_quality)) print(f"Processing {len(samples)} samples across {len(loci)} loci with {jobs} worker(s)...", file=sys.stderr) if jobs == 1: results = [] @@ -4494,10 +6272,15 @@ def _generate_provenance(args: argparse.Namespace) -> str: f"primer_mismatches={args.primer_mismatches}", f"gapped_rescue={args.gapped_rescue}", f"max_indel_length={args.max_indel_length}", + f"tile_groups={args.tile_groups}", f"annotations={args.annotations}", f"partial_read_mode={args.partial_read_mode}", f"min_partial_length={args.min_partial_length}", - *([f"leading_anchor={args.leading_anchor.upper()}"] if getattr(args, "leading_anchor", None) else []), + *( + [f"leading_anchor={args.leading_anchor.upper()}", f"leading_anchor_mismatches={args.leading_anchor_mismatches}"] + if getattr(args, "leading_anchor", None) else [] + ), + *(["remove_primers=on"] if args.remove_primers == "on" else []), # absent when off: the default line is unchanged f"denoise_distance={args.denoise_distance}", f"global_denoise_distance={args.global_denoise_distance}", f"denoise_alpha={args.denoise_alpha}", @@ -4523,6 +6306,7 @@ def _output_options(args: argparse.Namespace, samples: Sequence[Sample], output: preamble=preamble, annotations=args.annotations == "on", variants_path=output.with_suffix(output.suffix + ".variants.csv"), + remove_primers=args.remove_primers == "on", ) @@ -4534,8 +6318,16 @@ def _read_accounting( return { "reads_total": total("reads_total"), "reads_no_leading_anchor": total("reads_no_leading_anchor"), + # Of the reads that went on past the anchor, those cut at a placement + # one substitution away (--leading-anchor-mismatches 1). + "reads_leading_anchor_mismatch": total("reads_leading_anchor_mismatch"), "reads_assigned_full_length": total("reads_assigned"), "reads_assigned_gapped": total("reads_assigned_gapped"), + # A read credited to several tiles of one family counts once above; + # these are the further credits. From here on the ledger counts + # (marker, read) credits, which equal reads for a panel without tiles. + "tile_extra_credits_full_length": total("tile_extra_credits"), + "tile_extra_credits_partial": total("partial_tile_extra_credits"), "reads_n_mapped": total("reads_n_mapped"), "reads_n_dropped": total("reads_n_dropped"), "partial_reads_added_to_counts": partial_summary.get("reads_assigned", 0), @@ -4556,11 +6348,14 @@ def _generate_parameters(args: argparse.Namespace, settings: AssignmentSettings, "primer_mismatches": args.primer_mismatches, "gapped_rescue": args.gapped_rescue, "max_indel_length": args.max_indel_length, + "tile_groups": args.tile_groups, "annotations": args.annotations, + "remove_primers": args.remove_primers, "partial_read_mode": args.partial_read_mode, "minimum_partial_length": args.min_partial_length, "leading_anchor": (getattr(args, "leading_anchor", None) or "").upper() or None, "leading_anchor_detected": bool(getattr(args, "leading_anchor_detected", False)), + "leading_anchor_mismatches": args.leading_anchor_mismatches if getattr(args, "leading_anchor", None) else None, "sample_denoise_distance": args.denoise_distance, "global_denoise_distance": args.global_denoise_distance, "denoise_alpha": args.denoise_alpha, @@ -4587,6 +6382,14 @@ def _write_json(path: Path, payload: Mapping[str, object]) -> None: def run_generate(args: argparse.Namespace) -> int: """The pipeline, stage by stage (see the module docstring).""" _resolve_generate_defaults(args) + if args.remove_primers == "on" and args.annotations == "off": + # Only the Variants column records which rows of a table without primers end at their right + # primer and which were read through an indel a primer verified. A table without it cannot + # be told from one with primers, and downstream tools would read some of those indels as substitutions. + raise MadcError( + "--remove-primers on cannot be combined with --annotations off: the Variants column is what tells " + "downstream tools how each row of a table without primers was read. Keep the annotations, or keep the primers." + ) loci = _define_panel(args) rule = _evidence_rule(args) samples, fastq_directory, metadata_paths = _discover_samples(args) @@ -4594,14 +6397,19 @@ def run_generate(args: argparse.Namespace) -> int: args, [Path(sample.fastq) for sample in samples], {tag[:LEADING_ANCHOR_PREFIX] for locus in loci for tag in (locus.ref_tag, locus.alt_tag)}, "generate", ) - settings = _assignment_settings(args) + families = tile_families(loci, args.tile_groups) + _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, + 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) @@ -4626,6 +6434,7 @@ def run_generate(args: argparse.Namespace) -> int: "panel_fingerprint_sha256": panel_fingerprint(loci), "parameters": _generate_parameters(args, settings, output), "loci": len(loci), + "tile_families": [[loci[index].marker for index in family] for family in families], "samples": len(samples), "read_accounting": _read_accounting(results, partial_summary, output_summary), "output_summary": output_summary, @@ -4636,11 +6445,38 @@ def run_generate(args: argparse.Namespace) -> int: ], } _write_json(qc_path, qc) + if "primer_removal" in output_summary: + 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: @@ -5034,6 +6870,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: @@ -5104,12 +6947,12 @@ def _add_design_command(subparsers) -> None: def _add_infer_design_command(subparsers) -> None: infer = subparsers.add_parser( "infer-design", - help="infer the reference-tag panel from the probe design and the reads when the primer file is unavailable", + help="infer the reference-tag panel from the probe design and reads when no primer file is available", description=( - "Infer each marker's Ref and Alt tags from the probe design and the reads, for panels whose primer " - "file is not available. Reads vote for each locus's tag window: exact prefix matches decide first, " - "and a fuzzy pass runs only for loci with no exact votes. Loci that cannot be resolved are left out " - "and listed, with the reason, in the QC report." + "Infer each marker's canonical Ref and Alt tags from the probe design and FASTQ reads when the " + "primer file is unavailable. Reads vote for candidate tag windows in two tiers: exact prefix matches " + "decide first, and a fuzzy pass runs only for loci with no exact votes. Unresolved loci are omitted " + "from the panel and logged with their reasons in the QC report." ), ) infer.add_argument("--probe-design", required=True, help="probe-design TSV or CSV with bracketed variants") @@ -5117,49 +6960,49 @@ def _add_infer_design_command(subparsers) -> None: infer.add_argument( "--leading-anchor", default=None, - help="constant sequence preceding the amplicon in raw deliveries, or 'auto' to detect it (see generate --leading-anchor); reads without it do not vote", + help="constant sequence before the amplicon in raw deliveries, or 'auto' to detect it (reads without an exact match do not vote)", ) infer.add_argument( "--tag-length", type=positive_int, default=TAG_LENGTH_DEFAULT, - help="reported tag length of the panel, e.g. 54, 81, or 109 (default: 81)", + help="tag length of the panel, e.g. 54, 81, or 109 (default: 81)", ) infer.add_argument( "--min-identity", type=probability, default=0.80, - help="minimum identity for fuzzy-pass votes, as in generate (default: 0.80)", + help="minimum identity for fuzzy-tier votes, matching generate (default: 0.80)", ) infer.add_argument( "--dominance-ratio", type=ratio_at_least_one, default=10.0, - help="a winning window must have at least this many times the runner-up's votes (default: 10)", + help="minimum vote ratio of the winning window over the runner-up (default: 10)", ) infer.add_argument( "--fuzzy-min-reads", type=nonnegative_int, default=30, - help="fuzzy-pass votes needed to resolve a locus with no exact votes; 0 disables the fuzzy pass (default: 30)", + help="minimum fuzzy-tier votes required to resolve a locus with no exact votes, or 0 to disable the fuzzy tier (default: 30)", ) infer.add_argument( "--fuzzy-min-samples", type=nonnegative_int, default=2, - help="distinct samples that must contribute fuzzy votes (default: 2)", + help="minimum distinct samples required to contribute fuzzy votes (default: 2)", ) infer.add_argument( "--anchor-min-length", type=positive_int, default=15, - help="shortest pseudo-primer anchor to try (default: 15)", + help="shortest synthetic assignment anchor to try (default: 15)", ) infer.add_argument( "--anchor-max-length", type=positive_int, default=30, - help="longest pseudo-primer anchor; an anchor always ends before the variant (default: 30)", + help="longest synthetic assignment anchor, always capped before the variant (default: 30)", ) _add_jobs_argument(infer) infer.add_argument("--output", required=True, help="reference-tag CSV to write") @@ -5172,11 +7015,10 @@ def _add_merge_pairs_command(subparsers) -> None: "merge-pairs", help="merge overlapping paired-end reads into single fragment reads", description=( - "Merge each overlapping R1/R2 pair into one fragment read, before normalize-reads or generate. R2 is " - "reverse-complemented and the best-scoring overlap is used (overlap length with a penalty for " - "each mismatch). Adapter read-through falls outside the " - "overlap and never reaches the merged read, so no adapter trimming is needed. Use this only when " - "mates overlap." + "Merge overlapping R1/R2 read pairs into single consensus fragments before running normalize-reads or " + "generate. R2 is reverse-complemented and aligned against R1 using the best-scoring overlap (overlap " + "length minus 5 per mismatch). Read-through adapter bases fall outside the overlap and are trimmed " + "automatically. Use only when mates overlap (or pass --unmerged pool for mixed libraries)." ), ) merge.add_argument("--fastq-dir", required=True, help="folder holding paired FASTQ(.gz) files") @@ -5184,17 +7026,24 @@ def _add_merge_pairs_command(subparsers) -> None: merge.add_argument("--r2-suffix", default="_R2.fastq.gz", help="filename suffix of the R2 mate (default: _R2.fastq.gz)") merge.add_argument( "--min-overlap", type=positive_int, default=15, - help="shortest overlap, in bases, that lets a pair merge (default: 15)", + help="minimum overlap length in bases required to merge a pair (default: 15)", ) merge.add_argument( "--max-mismatch-rate", type=float, default=0.1, - help="mismatch fraction tolerated inside the overlap (default: 0.1)", + help="maximum mismatch fraction tolerated inside the overlap (default: 0.1)", ) merge.add_argument( "--unmerged", choices=("r1", "pool", "drop"), default="r1", help=( - "pairs that do not merge: keep the R1 (default), keep both mates (pool; for dual-anchored " - "designs whose mates cover opposite halves of the locus), or drop the pair" + "handling of unmerged pairs: r1 keeps R1, pool keeps both mates as separate single-end reads " + "(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) @@ -5205,66 +7054,64 @@ def _add_merge_pairs_command(subparsers) -> None: def _add_window_scan_command(subparsers) -> None: scan = subparsers.add_parser( "window-scan", - help="try several tag lengths on a subset of samples and recommend one", + help="evaluate candidate tag lengths on a sample subset and recommend one", description=( - "Run normalize-reads and generate at each candidate tag length on a subset of samples, measure " - "read retention, cleanliness and haplotype information, and recommend a length. Use it before " - "the first normalize-reads run of a new panel." + "Run normalize-reads and generate across candidate tag lengths on a representative sample subset, " + "measure read retention, assignment rate, cleanliness, and novel information rate, and recommend an " + "optimal window length before the first normalize-reads run of a new panel." ), ) scan.add_argument("--probe-design", required=True, help="probe-design TSV or CSV with bracketed variants") _add_fastq_arguments(scan) scan.add_argument( "--lengths", required=True, - help="comma-separated candidate tag lengths to run in full, e.g. 41,61,81,110", + help="comma-separated candidate tag lengths to evaluate in full, e.g. 41,61,81,110", ) scan.add_argument( "--scan-seed", type=int, default=None, - help="draw the --scan-samples subset at random with this seed instead of taking the first files in sorted order", + help="random seed for drawing the --scan-samples subset instead of taking the first sorted files", ) scan.add_argument( "--generate-args", default="", - help="extra generate flags for every candidate run, quoted as one string (e.g. \"--min-supporting-freq 0.1\")", + help="extra generate flags passed to every candidate run, quoted as one string (e.g. \"--min-supporting-freq 0.1\")", ) scan.add_argument( "--scan-samples", type=positive_int, default=6, - help="number of samples each candidate runs on: the first in sorted order, or a --scan-seed draw (default: 6)", + help="number of samples evaluated per candidate length, using the first sorted files or a --scan-seed draw (default: 6)", ) scan.add_argument( "--scan-draws", type=positive_int, default=1, help=( - "independent sample draws to sweep (seeds --scan-seed, +1, +2, ...; default: 1); with more than one, " - "each draw's recommendation and their agreement are reported, so you can see whether the " - "recommendation depends on which samples were scanned" + "number of independent sample draws using seeds --scan-seed (or 0), +1, +2, and so on. With multiple " + "draws, the report records each draw's recommendation and stability across draws (default: 1)" ), ) scan.add_argument( "--grid-step", type=positive_int, default=10, - help="step for the dense predicted-retention grid from the coverage pass (default: 10)", + help="step size for the dense predicted-retention grid from the coverage pass (default: 10)", ) scan.add_argument( "--info-band", type=probability, default=0.10, help=( - "survival tolerance for the information tiebreak: candidates within this fraction of " - "the best survival (retention x assignment x cleanliness) are eligible, and the most " - "informative eligible length is recommended (default: 0.10)" + "select the most informative length whose survival (retention x assignment x cleanliness) falls " + "within this fraction of the maximum survival (default: 0.10)" ), ) scan.add_argument( "--anchor-length", type=positive_int, default=12, - help="as in normalize-reads; used for the coverage pass and every candidate run (default: 12)", + help="same as normalize-reads, applied to the coverage pass and every candidate run (default: 12)", ) scan.add_argument( "--kmer-size", type=positive_int, default=21, - help="as in normalize-reads; used for the coverage pass and every candidate run (default: 21)", + help="same as normalize-reads, applied to the coverage pass and every candidate run (default: 21)", ) scan.add_argument( "--str-penalty", type=float, default=0.002, - help="as in normalize-reads; used for the coverage pass and every candidate run (default: 0.002)", + help="same as normalize-reads, applied to the coverage pass and every candidate run (default: 0.002)", ) scan.add_argument( "--group-routing", choices=("nearest", "covered"), default="nearest", - help="passed to the candidate normalize-reads runs; use covered for merged, tiled input (default: nearest)", + help="passed to candidate normalize-reads runs (use covered for merged, tiled input) (default: nearest)", ) _add_jobs_argument(scan) scan.add_argument("--out-dir", required=True, help="folder for per-length runs and the scan report") @@ -5274,12 +7121,13 @@ def _add_window_scan_command(subparsers) -> None: def _add_normalize_reads_command(subparsers) -> None: normalize = subparsers.add_parser( "normalize-reads", - help="orient and window reads that do not start at a primer (e.g. AgriSeq), ready for generate", + help="orient and window reads that do not start at a fixed primer (e.g. AgriSeq) for generate", description=( - "For platforms such as AgriSeq (Ion Torrent) whose reads do not start at a fixed primer. Each read " - "is located against the probe-design targets, oriented forward, and cut to a fixed-length window " - "containing the variant. Writes one FASTQ per sample plus a window reference-tags CSV, ready for " - "generate. Pass the first run's CSV to later runs with --reuse-tags." + "Normalize reads from platforms such as AgriSeq (Ion Torrent) or Flex-Seq that do not begin at a " + "fixed primer boundary. Uses a k-mer lookup table built from probe-design targets to locate each " + "read, re-orient it to the forward strand, and excise a fixed-length window surrounding the target " + "variant. Writes normalized per-sample FASTQs and a window reference-tags CSV for generate. Reuse the " + "baseline CSV on subsequent batches with --reuse-tags." ), ) normalize.add_argument("--probe-design", required=True, help="probe-design TSV or CSV with bracketed variants") @@ -5288,16 +7136,16 @@ def _add_normalize_reads_command(subparsers) -> None: "--tag-length", type=positive_int, default=41, - help="window length to cut; shorter windows lose fewer reads to indels on indel-prone chemistries (default: 41)", + help="excised window length in bases (shorter windows lose fewer reads on indel-prone chemistries) (default: 41)", ) normalize.add_argument( "--window-placement", choices=("auto", "center"), default="auto", help=( - "auto learns each marker's window from observed read coverage (extra pass); center needs no read data " - "(default: auto). With --reuse-tags the windows are fixed, and auto instead runs the pass to score " - "the frozen windows against this run's reads (freeze_health in the QC); center skips it" + "auto learns each marker's window from read coverage (one extra pass), while center uses the target " + "midpoint without scanning reads. With --reuse-tags, auto scores the frozen windows against the new " + "reads (freeze_health in QC) and center skips scoring (default: auto)" ), ) normalize.add_argument( @@ -5305,16 +7153,15 @@ def _add_normalize_reads_command(subparsers) -> None: type=positive_int, default=12, help=( - "minimum assignment-anchor prefix length; anchors grow per locus only where window " - "prefixes collide, and the variant is always kept out of the anchor (default: 12)" + "minimum synthetic assignment anchor length. Anchors grow per locus only where window prefixes " + "collide and never include the target variant (default: 12)" ), ) normalize.add_argument( "--reuse-tags", help=( - "window reference-tags CSV from a previous normalize-reads run to reuse verbatim, freezing " - "window placement across runs of the same panel so microhaplotype sequences stay comparable " - "(--anchor-length is ignored; --window-placement auto scores the frozen windows, center skips that)" + "baseline window reference-tags CSV from an earlier normalize-reads run to reuse verbatim so " + "microhaplotype definitions stay consistent across batches (--anchor-length is ignored)" ), ) normalize.add_argument( @@ -5322,11 +7169,9 @@ def _add_normalize_reads_command(subparsers) -> None: choices=("nearest", "covered"), default="nearest", help=( - "how a read covering several windows of one LocusGroup is routed: 'nearest' (default) sends it " - "to the one tile whose window center is nearest the read's center; 'covered' cuts a window at " - "every tile the read fully covers. Use covered with merged full-span fragments: they all share " - "the amplicon's center, so with nearest one tile would get almost every read. In both modes " - "each window counts each fragment at most once" + "routing for reads covering multiple windows in a LocusGroup: nearest assigns the read to the tile " + "whose window center is closest to the read's center, while covered excises a window at every tile " + "the read fully covers (recommended for merged full-span fragments) (default: nearest)" ), ) normalize.add_argument( @@ -5334,16 +7179,15 @@ def _add_normalize_reads_command(subparsers) -> None: type=float, default=0.002, help=( - "auto placement: coverage penalty per tandem-repeat bp (unit sizes 1-3) beyond 4 in a candidate " - "window; steers windows away from repeats where reads carrying one allele are lost more often " - "(0 disables; default: 0.002)" + "auto placement coverage penalty per tandem-repeat base (1-3 bp units) beyond 4 bp in a candidate " + "window to steer windows away from repeats, or 0 to disable (default: 0.002)" ), ) normalize.add_argument( "--kmer-size", type=positive_int, default=21, - help="k-mer length for locating reads against the design targets (default: 21)", + help="k-mer length used to locate reads against probe-design targets (default: 21)", ) _add_jobs_argument(normalize) normalize.add_argument("--out-dir", required=True, help="folder for the normalized per-sample FASTQs") @@ -5356,13 +7200,13 @@ def _add_generate_command(subparsers) -> None: """``generate``'s options, grouped by the pipeline stage each one feeds.""" generate = subparsers.add_parser( "generate", - help="count alleles in every sample and write the MADC table", + help="assign reads, discover microhaplotypes, denoise errors, and write the MADC table", description=( - "Assign reads to markers, count exact tag sequences per sample, report new microhaplotypes that " - "pass the evidence rules, remove sequencing errors by denoising, and write a raw MADC table plus " - "a QC/provenance JSON. Run one generate over the whole cohort: the reproducibility route counts " - "supporting samples within the run. The raw MADC goes through HapApp before BIGr and other " - "downstream tools." + "Assign reads to target loci, count exact tag sequences per sample, discover novel microhaplotypes " + "passing the evidence rules, merge sequencing errors by denoising, and write a raw MADC table along " + "with a QC/provenance JSON. Process the full cohort in a single generate invocation so the " + "reproducibility route evaluates all samples together. Pass the raw MADC through HapApp before using " + "BIGr or other downstream tools." ), ) panel = generate.add_argument_group("panel and samples (stage 1)") @@ -5371,15 +7215,12 @@ def _add_generate_command(subparsers) -> None: panel.add_argument("--probe-design", help="DArT probe-design TSV or CSV (use with --primers)") panel.add_argument( "--reference-tags", - help=( - "reference-tag CSV from design, infer-design or normalize-reads, or curated by hand; " - "use instead of --primers/--probe-design" - ), + help="reference-tag CSV from design, infer-design, or normalize-reads (use instead of --primers/--probe-design)", ) panel.add_argument( "--target-metadata", nargs="*", - help="target-manifest CSV(s); defaults to targets_*.csv in the FASTQ folder", + help="target-manifest CSV(s) (default: targets_*.csv in the FASTQ folder)", ) panel.add_argument( "--sample-name-field", @@ -5389,16 +7230,15 @@ def _add_generate_command(subparsers) -> None: panel.add_argument( "--sample-lookup", help=( - "two-column CSV/TSV mapping FASTQ-derived sample ids to sample names; replaces the output " - "column names (every run sample must be mapped) while the preamble targetid row keeps the " - "FASTQ ids, matching the raw-MADC layout" + "two-column CSV/TSV mapping every run's FASTQ sample ID to its output sample name (renames sample " + "columns while keeping FASTQ IDs in the preamble targetid row)" ), ) panel.add_argument( "--tag-length", type=positive_int, default=TAG_LENGTH_DEFAULT, - help=f"tag length; must match the panel, e.g. 41 after normalize-reads (default: {TAG_LENGTH_DEFAULT})", + help=f"tag length matching the panel, e.g. 41 after normalize-reads (default: {TAG_LENGTH_DEFAULT})", ) assignment = generate.add_argument_group("read assignment (stage 2)") @@ -5407,47 +7247,63 @@ def _add_generate_command(subparsers) -> None: type=probability, default=0.80, help=( - "minimum identity to the marker's Ref or Alt tag, counting substitutions only; a gapped " - "alignment uses the same edit limit (default: 0.80)" + "minimum substitution-only identity to the marker's Ref or Alt tag. Gapped alignments use the same " + "edit limit (default: 0.80)" ), ) assignment.add_argument( "--leading-anchor", default=None, help=( - "constant sequence that precedes the amplicon in every read of a raw delivery (DArT raw " - "FASTQs carry an inline barcode and the common sequence GATGGATCCAGTGC); each read is cut " - f"to start right after its first occurrence within the first {LEADING_ANCHOR_SEARCH} bases " - "beyond the anchor's length, and reads without it are counted as reads_no_leading_anchor; " - "'auto' detects the anchor from the first FASTQ (default: none; preprocessed deliveries are " - "primer-started, and a run whose reads carry an undeclared constant prefix stops and names it)" + "constant sequence preceding the amplicon in raw deliveries (DArT: GATGGATCCAGTGC). Cuts each read " + f"where the anchor ends. 'auto' detects it from up to {LEADING_ANCHOR_FILES} FASTQs. Without this " + "option, raw deliveries stop with an error naming the detected anchor (default: none)" ), ) assignment.add_argument( - "--primer-mismatches", + "--leading-anchor-mismatches", type=int, choices=(0, 1), - default=1, + default=LEADING_ANCHOR_MISMATCHES_DEFAULT, help=( - "mismatches allowed when matching a read's start to a primer/anchor (default: 1). With 0, " - "reads from Match haplotypes whose distinguishing SNP falls inside the anchor are lost" + "substitutions allowed in the leading anchor. With 1, reads lacking an exact match are cut after " + "their unique one-substitution placement. Anchors under " + f"{LEADING_ANCHOR_MISMATCH_MIN_LENGTH} bases always require an exact match " + f"(default: {LEADING_ANCHOR_MISMATCHES_DEFAULT})" ), ) + assignment.add_argument( + "--primer-mismatches", + type=int, + choices=(0, 1), + default=1, + help="mismatches allowed when matching a read's start to a left primer or anchor (default: 1)", + ) assignment.add_argument( "--gapped-rescue", choices=("on", "off"), default="on", help=( - "give reads that fail the substitution-only identity check for every marker one gapped " - "alignment under the same edit limit, so undesigned indels are counted instead of dropped " - "(default: on)" + "attempt one banded gapped alignment for reads failing the substitution-only identity check across " + "all candidate markers, and classify targets and Variants through accepted gaps. With off, rows are " + "read at fixed offsets, which can misclassify indel rows (default: on)" ), ) assignment.add_argument( "--max-indel-length", type=positive_int, default=GAP_BAND_DEFAULT, - help=f"widest gap (alignment band) a gapped alignment may use (default: {GAP_BAND_DEFAULT})", + help=f"maximum gap length (alignment band width) allowed during gapped alignment (default: {GAP_BAND_DEFAULT})", + ) + assignment.add_argument( + "--tile-groups", + choices=("auto", "declared", "off"), + default="auto", + help=( + "credit reads matching multiple tiled markers from the same amplicon to each matching tile instead of " + "dropping them as ties: auto links declared LocusGroup tiles and detects undeclared ones, declared " + "links only declared groups, and off disables tile linking (default: auto)" + ), ) assignment.add_argument( "--partial-read-mode", @@ -5455,90 +7311,83 @@ def _add_generate_command(subparsers) -> None: choices=("on", "off"), default="on", help=( - "handling of reads shorter than --tag-length: on adds such a read to the one full-length " - "allele whose start it matches exactly, only when that allele already passes the evidence rules " - "and the read is longer than every prefix shared between that locus's alleles, so partial reads " - "cannot create an allele or change an allele ratio (default: on); off drops them" + "on credits reads shorter than --tag-length to a single evidence-passing allele whose prefix they " + "match, provided the read is longer than any prefix shared by two alleles at that locus. off discards " + "partial reads (default: on)" ), ) assignment.add_argument( "--min-partial-length", type=positive_int, default=None, + help="minimum read length salvaged when --partial-read-mode is on (default: --tag-length minus 9)", + ) + assignment.add_argument( + "--cache-dir", help=( - "minimum length for a partial read to be counted with --partial-read-mode on " - "(default: --tag-length minus 9)" + "folder for reusable per-sample assignment caches so reruns skip the read pass. A cache is reused " + "only when the panel, tile families, --tag-length, --min-identity, --leading-anchor (and its " + "mismatches), --primer-mismatches, --gapped-rescue, --max-indel-length, and --min-partial-length match" ), ) assignment.add_argument( - "--cache-dir", + "--cache-gzip-level", type=compression_level, default=GZIP_LEVEL_DEFAULT, metavar="1-9", help=( - "folder for a reusable per-sample cache, so re-runs skip the read pass. The cache is rebuilt " - "when the panel or --tag-length, --min-identity, --leading-anchor, --primer-mismatches, " - "--gapped-rescue, --max-indel-length or --min-partial-length changes" + "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 new sequences are reported)") + evidence = generate.add_argument_group("evidence (stage 4: which novel sequences become rows)") evidence.add_argument( "--min-global-count", type=positive_int, default=1, - help="minimum project-wide reads for a newly discovered allele (default: 1)", + help="minimum total reads across the project required for a novel allele (default: 1)", ) evidence.add_argument( "--reproducible-min-reads", type=positive_int, default=10, - help="reproducibility route: reads per sample counted toward --reproducible-min-samples (default: 10)", + help="reproducibility route: minimum reads a sample needs to count toward --reproducible-min-samples (default: 10)", ) evidence.add_argument( "--reproducible-min-samples", type=nonnegative_int, default=2, help=( - "reproducibility route: a new allele needs at least --reproducible-min-reads reads in at " - "least this many samples; 0 disables the route (default: 2)" + "reproducibility route: minimum samples required with at least --reproducible-min-reads reads, or 0 " + "to disable the route (default: 2)" ), ) evidence.add_argument( "--depth-min-reads", type=nonnegative_int, default=30, - help=( - "depth route: reads within one sample that are enough on their own to report a new allele, so " - "alleles found in only one sample can still be reported when samples are not replicated; " - "0 disables the route (default: 30)" - ), + help="depth route: reads in a single sample sufficient to report a novel allele, or 0 to disable (default: 30)", ) evidence.add_argument( "--discovery-min-quality", type=int, choices=QUALITY_THRESHOLDS, default=20, - help="Phred score every tag base must reach for a read to count as high-quality on the quality route (default: 20)", + help="quality route: minimum Phred score every tag base must meet for a read to count as clean (default: 20)", ) evidence.add_argument( "--quality-min-clean-reads", type=nonnegative_int, default=0, - help=( - "quality route: project-wide high-quality reads that are enough on their own to report a new " - "allele; 0 disables the route (default: 0). Off by default because one systematically " - "low-quality base position would block real alleles; reproducibility is the main route" - ), + help="quality route: project-wide clean reads sufficient to report a novel allele, or 0 to disable (default: 0)", ) evidence.add_argument( "--min-supporting-freq", type=proper_fraction, default=0.0, help=( - "minimum share of a sample's reads at the locus before that sample can count toward the " - "reproducibility or depth route; 0 disables the floor (default: 0). Use 0.10 at very high depth " - "(above ~500x per sample per marker, e.g. AgriSeq), or about 0.01 for unreplicated designs that " - "rely on the depth route. Otherwise leave it off: co-amplified paralogs lower real alleles' " - "shares, so a floor can drop them" + "minimum fraction of a sample's locus reads required before that sample supports a novel allele in " + "the reproducibility or depth route, or 0 to disable. Use 0.10 above ~500x per sample per marker " + "(default: 0)" ), ) @@ -5549,8 +7398,8 @@ def _add_generate_command(subparsers) -> None: choices=(0, 1, 2), default=1, help=( - "per-sample denoising: the most differing bases allowed between a rare sequence and the more " - "abundant parent it is merged into; 0 disables (default: 1)" + "per-sample denoising: maximum substitutions between a rare sequence and the more abundant parent it " + "merges into, or 0 to disable (default: 1)" ), ) denoising.add_argument( @@ -5559,16 +7408,15 @@ def _add_generate_command(subparsers) -> None: choices=(0, 1, 2), default=1, help=( - "pooled same-allele merge: a sequence that failed the evidence rules and differs at no more " - "than this many bases from a protected parent carrying the same target allele is merged into " - "it in every sample; 0 disables (default: 1)" + "pooled merge: maximum substitutions between an evidence-failing sequence and a protected or " + "canonical parent carrying the same target allele, or 0 to disable (default: 1)" ), ) denoising.add_argument( "--denoise-alpha", type=float, default=2.0, - help="UNOISE-style abundance-skew exponent: a parent must be at least 2^(alpha*d + 1) times more abundant (default: 2.0)", + help="UNOISE2 abundance-skew exponent: a parent needs at least 2^(alpha*d + 1) times the child's reads (default: 2.0)", ) output = generate.add_argument_group("output (stages 6-7)") @@ -5579,25 +7427,30 @@ def _add_generate_command(subparsers) -> None: choices=("on", "off"), default="on", help=( - "annotate every row in two otherwise unused statistics columns and a sidecar file: PICSnp becomes " - "Variants (the row's events against the Ref tag in 1-based tag coordinates, e.g. " - "55:C>CAAAA;91:A>T;clip=4), AvgPIC becomes MarkerType ('.', 'snp', 'indel' or 'both' relative " - "to the nearest canonical), and OUTPUT.variants.csv lists one event per line; 'off' keeps the " - "exact vendor header and writes no sidecar (default: on)" + "replace PICSnp with Variants (events against the Ref tag, e.g. 55:C>CAAAA;91:A>T;clip=4) and AvgPIC " + "with MarkerType ('.', snp, indel, both, or unresolved), and write one event per line to " + "OUTPUT.variants.csv. With off, keep the exact vendor header (default: on)" + ), + ) + output.add_argument( + "--remove-primers", + choices=("on", "off"), + default="off", + help=( + "trim primer sequences from emitted rows and sum counts for rows that become identical. Assignment, " + "counting, denoising, and classification still run on the full tags. Requires --annotations on " + "(default: off)" ), ) output.add_argument( "--number-match-ids", action="store_true", - help="append a stable serial to each RefMatch/AltMatch/Other ID (e.g. |RefMatch_0001) so every AlleleID is unique", + help="append a stable serial number to each RefMatch, AltMatch, and Other ID (e.g. |RefMatch_0001) so every AlleleID is unique", ) output.add_argument( "--dart-preamble", action="store_true", - help=( - "prepend the vendor-style seven-row starred preamble (service label, plate rows, and a " - "targetid row with the FASTQ-derived sample ids) that HapApp expects" - ), + help="prepend the seven vendor-style starred preamble rows expected by HapApp", ) output.add_argument( "--preamble-project", @@ -5609,19 +7462,19 @@ def _add_generate_command(subparsers) -> None: def _add_validate_command(subparsers) -> None: validate = subparsers.add_parser( "validate", - help="compare a generated MADC with a reference MADC", + help="compare a generated MADC against a reference MADC", description=( - "Compare a generated MADC with a reference MADC, usually the vendor's delivery for the same " - "FASTQs: row precision and recall by allele category, classification agreement on shared rows, " - "and count agreement across shared cells. The report is printed as JSON. The reference MADC is " - "used only for this comparison." + "Compare a generated MADC against a reference MADC (typically a vendor delivery from the same FASTQ " + "files), reporting row precision and recall by allele category, classification agreement on shared " + "rows, and read-count agreement across shared cells as JSON. The reference MADC is used strictly for " + "evaluation." ), ) validate.add_argument("--generated", required=True, help="MADC table written by generate") validate.add_argument( "--expected", required=True, - help="reference MADC to compare against, with or without the vendor's starred preamble rows", + help="reference MADC to compare against, with or without vendor starred preamble rows", ) validate.add_argument("--report", help="also write the JSON report to this file") validate.set_defaults(func=run_validate) @@ -5633,16 +7486,17 @@ def build_parser() -> argparse.ArgumentParser: formatter_class=argparse.RawDescriptionHelpFormatter, description=( "MADCATS (Marker-Anchored Discovery and Counting of Alleles from Targeted\n" - "Sequencing) turns targeted-sequencing FASTQs into raw MADC tables: the\n" - "microhaplotypes at each marker and their read counts in every sample. It\n" - "counts the alleles each panel was designed for and discovers new ones." + "Sequencing) converts targeted-sequencing FASTQ files into raw MADC tables\n" + "recording microhaplotypes and per-sample read counts for each marker. It\n" + "counts designed alleles and discovers novel microhaplotypes from the reads." ), epilog=( "typical workflow:\n" - " 1. build the panel design, or infer-design without a primer file\n" - " 2. prepare reads if needed merge-pairs, window-scan, normalize-reads\n" - " 3. count generate\n" - " 4. check (optional) validate\n" + " 1. build the panel design, or infer-design without a primer file\n" + " 2. prepare reads if needed merge-pairs, window-scan, normalize-reads\n" + " 3. count generate\n" + " 4. filter paralogs (optional) filter-paralogs (experimental, requires mappy)\n" + " 5. check (optional) validate\n" "\n" "Run 'madcats --help' for a command's options.\n" "Documentation: https://madcats.readthedocs.io" @@ -5657,6 +7511,9 @@ def build_parser() -> argparse.ArgumentParser: _add_normalize_reads_command(subparsers) _add_generate_command(subparsers) _add_validate_command(subparsers) + import madcats_paralogs # here, not at the top: it imports this module + + madcats_paralogs.add_filter_paralogs_command(subparsers) return parser @@ -5670,4 +7527,7 @@ def main(argv: Optional[Sequence[str]] = None) -> int: if __name__ == "__main__": + # Run as a script, this file is __main__; madcats_paralogs's "import madcats" + # must find it rather than load a second copy with its own MadcError. + sys.modules.setdefault("madcats", sys.modules[__name__]) raise SystemExit(main()) diff --git a/madcats_paralogs.py b/madcats_paralogs.py new file mode 100644 index 0000000..695e9a4 --- /dev/null +++ b/madcats_paralogs.py @@ -0,0 +1,1042 @@ +"""``madcats filter-paralogs``: clean a finished MADC with a reference genome. + +In panels where paralogous copies co-amplify with a target, a paralog read +that differs from the Ref tag only at non-target bases becomes a RefMatch or +AltMatch row of that marker. This module places each marker on the genome +by its Ref tag and, for CHROM_POS CloneIDs, by that position (see +``--clone-positions``); aligns every haplotype; and drops or flags the rows +whose best alignment lies at another locus (paralogs) or ties between loci +(ambiguous). + +It is kept apart from ``madcats.py`` because it is the only command with a +dependency outside the standard library: the ``mappy`` aligner (minimap2), +imported on first use (``pip install 'madcats[genome]'``), so ``madcats`` +runs without it. The MADC reading helpers it shares with ``validate`` +(header detection, sample columns, allele categories, the count-overflow +check) stay in ``madcats``. + +What is minimap2's and what is this module's. Alignment is minimap2's, +through its Python binding mappy (MIT licence; https://github.com/lh3/minimap2): + + Li H (2018) Minimap2: pairwise alignment for nucleotide sequences. + Bioinformatics 34(18):3094-3100. doi:10.1093/bioinformatics/bty191 + Li H (2021) New strategies to improve minimap2 alignment accuracy. + Bioinformatics 37(23):4572-4574. doi:10.1093/bioinformatics/btab705 + +The index (k=21, w=11) and the alignment scores are those of minimap2's +short-read preset (``-x sr``). Three of the preset's mapping options are +changed for the genome-wide search (``GENOME_WIDE_MAP_OPTIONS``). The layout +of an index file read by ``_index_part_contigs`` is that written by +minimap2's ``mm_idx_dump`` (index.c). Everything else is MADCATS's own, with +no published counterpart: the score recomputed from an alignment +(``hit_score``), the rule for when two alignments are one locus, the +realignment of every haplotype at its own marker's site with short seeds, +marker placement with the CloneID position, and the labels. The label rule +began as "a read whose best alignment score exceeds its second best", as +bwa mem reports them, in a prototype that is not part of MADCATS; here the +comparison is between the marker's own site and anywhere else. The +measurements behind the choices are in docs/DEVELOPMENT.md ("Genome paralog +filter"). + +Reading map: scoring and alignment (``hit_score``, ``GenomeAligner``, +``WindowIndex``, ``map_sequences``); marker placement and labels +(``place_marker``, ``score_at_sites``, ``genome_label``); the two passes over +the table (``_read_haplotypes``, ``_write_filtered_table``) and the function +that joins them (``filter_paralogs``); the command line +(``add_filter_paralogs_command``, ``run_filter_paralogs``). +""" + +from __future__ import annotations + +import argparse +import concurrent.futures +import csv +import datetime as dt +import re +import struct +import sys +import time +from collections import Counter, defaultdict +from pathlib import Path +from typing import Callable, Dict, Iterable, List, Mapping, NamedTuple, Optional, Sequence, Set, Tuple + +from madcats import ( + CountOverflowCheck, + MadcError, + __version__, + _default_jobs, + _write_json, + allele_type, + is_madc_header, + madc_identity_columns, + madc_read_counts, + madc_sample_start, + open_text, + positive_int, +) + +# In flag mode the label goes into the column of this vendor statistic, which is renamed. +REPLACED_STATISTICS_COLUMN = "PICRef" +GENOME_LABEL_COLUMN = "GenomeLabel" + +# The alignment scores of minimap2's short-read preset (-x sr): match, mismatch, gap open, gap +# extend, long-gap open, long-gap extend; and minimap2's general score for an ambiguous base. +# They are passed to the aligner, although they are its preset's values, so that hit_score and +# the aligner cannot come to differ. +SHORT_READ_SCORING = (2, 8, 12, 2, 24, 1, 1) +# The index of that preset: minimizers of 21 bases in windows of 11. +SHORT_READ_INDEX_K_W = (21, 11) +# Changes to the preset's mapping options for the genome-wide search (the index is unchanged): +# chains of a single seed (the preset needs 2), a lower least chain score (25) and up to 50 +# secondary hits (20), so 51 hits in all. An 81-base allele with several SNPs then still finds +# its copies. Chosen on the lettuce MADCATS MADC, where the rows kept or dropped agreed with a +# bwa mem classification for 98.2% of rows, against 97.3% with the preset's values +# (docs/DEVELOPMENT.md). The realignment at a marker's site keeps the preset's values. +GENOME_WIDE_MAP_OPTIONS = {"min_cnt": 1, "min_chain_score": 20, "best_n": 50} +# Distinct genome sites remembered per haplotype, best first. Ref tags keep all of theirs. +MAX_SITES_PER_HAPLOTYPE = 8 +# Sequences handed to a worker thread at a time. +MAPPING_BATCH = 2000 + +# A CloneID of the form CHROM_POS; the position may be zero-padded. +CLONE_POSITION_RE = re.compile(r"(.+)_0*(\d+)") +# A CloneID position up to this many bases outside a site still counts as at that site. +CLONE_POSITION_SLACK = 10 +# More than this share of CloneID positions away from their Ref tags' sites brings a warning +# that the positions may refer to another assembly. +CLONE_DISAGREEMENT_WARNING_SHARE = 0.1 + +# The realignment of a haplotype at its own marker's site: the site with this many genome bases +# either side, indexed with minimizers of 11 bases in windows of 3, so that an allele too +# diverged to seed in the genome-wide search (21 bases) still aligns where it belongs. The +# rest of the genome is searched with the longer seeds only, so a copy elsewhere that is as +# diverged as that may go unfound. +SITE_FLANK = 20 +SITE_INDEX_K, SITE_INDEX_W = 11, 3 + +# CIGAR operations as mappy numbers them. +CIGAR_INSERTION, CIGAR_DELETION = 1, 2 +# A minimap2 index file: the bytes each part starts with, and the flag of a part stored +# without its sequences (MM_I_NO_SEQ). +INDEX_PART_MAGIC = b"MMI\x02" +INDEX_WITHOUT_SEQUENCES = 2 + +# The labels sidecar's Action column holds what was done with the row: kept, flagged, +# protected or dropped. +LABELS_SIDECAR_COLUMNS = [ + "CloneID", "AlleleID", "AlleleSequence", "Label", "Action", + "TargetScore", "TargetFrom", "OffTargetScore", "OffTargetSites", "OffTargetHit", +] +MARKERS_SIDECAR_COLUMNS = ["CloneID", "Placement", "RefTagSites", "CloneIDCheck", "Sites"] + + +class GenomeHit(NamedTuple): + """One alignment to the genome: a 0-based, half-open interval, its strand (1 or -1) and its score. + + Also used for a genome window that stands in for a site, with strand 0 and score 0. + """ + + contig: str + start: int + end: int + strand: int + score: int + + +class GenomePlacement(NamedTuple): + """A sequence's distinct genome sites, best score first (hits overlapping a better one are merged into it).""" + + sites: Tuple[GenomeHit, ...] + + @property + def equal_best(self) -> Tuple[GenomeHit, ...]: + """The sites that share the best score.""" + return tuple(site for site in self.sites if site.score == self.sites[0].score) + + +class MarkerPlacement(NamedTuple): + """Where a marker's own tag lies in the genome. + + ``placed_by`` (the markers sidecar's Placement column): ``ref_tag`` (the + Ref tag has one best site), ``ref_tag+clone_id`` (several equal-best + sites; the CloneID position picks one), ``ref_tag_multicopy`` (several, + none picked: every site is the marker's), ``clone_id_site`` (no + equal-best site is at the CloneID position; the Ref tag's alignment + within a window around it), ``clone_id`` (the Ref tag did not align; the + window around the CloneID position stands in) or ``unplaced``. + ``ref_tag_site_count`` is the number of equal-best genome sites of the Ref + tag, whichever of them became ``sites``. ``clone_id_check`` compares the + CloneID position with the Ref-tag sites: ``agree``, ``disagree``, + ``no_position`` (the CloneID is not CHROM_POS), ``contig_absent``, + ``fallback``, or ``ignored`` (``--clone-positions ignore``). + """ + + sites: Tuple[GenomeHit, ...] + placed_by: str + ref_tag_site_count: int + clone_id_check: str + + +class GenomeLabel(NamedTuple): + """A haplotype's label and the two scores that decided it. + + The fields after the label are the labels sidecar's columns of the same + names. ``target_score`` is the best alignment at the marker's own site + and ``target_from`` says which search gave it: ``genome`` (the + genome-wide search), ``site`` (the realignment at the site, which scored + higher or was the only one to align there) or ``.`` (none). + ``off_target_score`` is the best alignment anywhere else, + ``off_target_sites`` the number of distinct sites elsewhere with that + score, among the at most ``MAX_SITES_PER_HAPLOTYPE`` sites kept, and + ``off_target_hit`` the first of them. + """ + + label: str + target_score: Optional[int] + target_from: str + off_target_score: Optional[int] + off_target_sites: int + off_target_hit: Optional[GenomeHit] + + +def hit_score(cigar: Sequence[Sequence[int]], edit_distance: int, matches: int, block_length: int) -> int: + """The score of an alignment under ``SHORT_READ_SCORING``, from what mappy reports of it. + + mappy returns an alignment's CIGAR, edit distance (NM), number of matching + bases and block length, but not minimap2's own alignment score (AS), so + the score is worked out here. As minimap2 defines them (``mm_update_extra`` + in align.c), the block length counts aligned columns and gap bases but + not columns with an ambiguous base, and NM counts all three kinds of + difference; hence mismatches = block - matches - gap bases, and ambiguous + columns = NM - (block - matches). A gap costs the cheaper of minimap2's + two affine pieces (Li 2018). Both differences are held at zero or above, + since a gap base that is itself ambiguous is not in the block length. + """ + (match_score, mismatch_penalty, gap_open_penalty, gap_extend_penalty, long_gap_open_penalty, + long_gap_extend_penalty, ambiguous_penalty) = SHORT_READ_SCORING + gap_bases = gap_cost = 0 + for length, operation in cigar: + if operation in (CIGAR_INSERTION, CIGAR_DELETION): + gap_bases += length + gap_cost += min( + gap_open_penalty + gap_extend_penalty * length, long_gap_open_penalty + long_gap_extend_penalty * length + ) + differences = block_length - matches + mismatches = max(0, differences - gap_bases) + ambiguous_bases = max(0, edit_distance - differences) + return match_score * matches - mismatch_penalty * mismatches - ambiguous_penalty * ambiguous_bases - gap_cost + + +def _same_locus(hit: GenomeHit, site: GenomeHit) -> bool: + """Whether two alignments are at one locus: their intervals share at least half of the shorter one. + + Adjacent tandem copies, which share a few bases, stay distinct. + """ + if hit.contig != site.contig: + return False + overlap = min(hit.end, site.end) - max(hit.start, site.start) + return overlap > 0 and 2 * overlap >= min(hit.end - hit.start, site.end - site.start) + + +def distinct_sites( + hits: Iterable[GenomeHit], max_sites: Optional[int] = MAX_SITES_PER_HAPLOTYPE +) -> GenomePlacement: + """A sequence's distinct genome sites, best first, at most ``max_sites`` of them (None: all). + + A hit at the same locus as a better-scoring one (``_same_locus``) is + merged into it. + """ + sites: List[GenomeHit] = [] + for hit in sorted(hits, key=lambda hit: (-hit.score, hit.contig, hit.start)): + if any(_same_locus(hit, site) for site in sites): + continue + sites.append(hit) + if len(sites) == max_sites: + break + return GenomePlacement(tuple(sites)) + + +def _index_part_contigs(path: Path) -> Optional[List[List[str]]]: + """The contig names in each part of a minimap2 index file, or None when the file is not one. + + minimap2 writes an index in one part for every ``-I`` bases of genome, + and mappy loads only the first part. The file is read as minimap2's + ``mm_idx_dump`` (index.c) writes it. Each part is: 4 bytes ``MMI\\2``; + five 32-bit words (window, k-mer length, bucket bits, number of + sequences, flags); for every sequence its name, preceded by the name's + length in one byte, and its length in 4 bytes; for every bucket two + counts, of 8-byte positions and of 16-byte hash entries; and, unless the + flags say the sequences are left out, the sequences at 4 bits a base in + 32-bit words. + """ + file_size = path.stat().st_size + with path.open("rb", buffering=0) as handle: + + def read_exactly(count: int) -> bytes: + data = handle.read(count) + if len(data) != count: + raise MadcError(f"{path} ends inside a minimap2 index part; rebuild the index") + return data + + def read_word() -> int: + return struct.unpack(" GenomeHit: + """A mappy alignment as a GenomeHit. ``contig`` and ``offset`` put a hit within a window on the genome.""" + return GenomeHit( + hit.ctg if contig is None else contig, offset + hit.r_st, offset + hit.r_en, hit.strand, + hit_score(hit.cigar, hit.NM, hit.mlen, hit.blen), + ) + + +def _load_mappy(): + try: + import mappy + except ImportError as exc: + raise MadcError( + "filter-paralogs needs the optional minimap2 aligner: pip install 'madcats[genome]' (or pip install mappy)" + ) from exc + return mappy + + +class GenomeAligner: + """The genome-wide search: minimap2's short-read preset through mappy, with + ``SHORT_READ_SCORING`` and the mapping options of ``GENOME_WIDE_MAP_OPTIONS``.""" + + def __init__(self, aligner, mappy_module) -> None: + self._aligner = aligner + self._mappy = mappy_module + self.contigs = frozenset(aligner.seq_names) + self.description = { + "mappy": getattr(mappy_module, "__version__", None), + "preset": "sr", + "k": aligner.k, + "w": aligner.w, + "scoring": list(SHORT_READ_SCORING), + "map_options": dict(GENOME_WIDE_MAP_OPTIONS), + "site_realignment": {"k": SITE_INDEX_K, "w": SITE_INDEX_W, "pad": SITE_FLANK}, + } + + @classmethod + def open(cls, genome: Optional[Path], index: Optional[Path], jobs: int) -> "GenomeAligner": + """Load ``index`` when it exists; otherwise index ``genome`` (saving to ``index`` when given).""" + mappy = _load_mappy() + if index is not None and index.exists(): + source, index_to_write = index, None + elif genome is not None: + source, index_to_write = genome, index + else: + raise MadcError(f"Genome index not found: {index} (pass --genome to build it)") + if not source.exists(): + raise MadcError(f"Genome file not found: {source}") + # The file may be an index whichever option named it; an index is loaded, never rebuilt. + parts = _index_part_contigs(source) + if parts is not None: + index_to_write = None + if index_to_write is not None: + index_to_write.parent.mkdir(parents=True, exist_ok=True) + if parts is not None and len(parts) > 1: + raise MadcError( + f"{source} is a minimap2 index in {len(parts)} parts ({sum(map(len, parts)):,} contigs), and mappy " + f"searches only the first ({len(parts[0]):,} contigs), so the rest of the genome would be missed. " + "Rebuild it as one part: give --genome and a new --genome-index path, or run minimap2 -x sr " + "with -I above the genome size" + ) + verb = "Loading index" if parts is not None else "Indexing genome" + print(f"{verb} {source}" + (f" (saving {index_to_write})" if index_to_write else ""), file=sys.stderr) + aligner = mappy.Aligner( + str(source), preset="sr", n_threads=jobs, fn_idx_out=str(index_to_write) if index_to_write else None, + scoring=list(SHORT_READ_SCORING), **GENOME_WIDE_MAP_OPTIONS, + ) + if not aligner: + raise MadcError(f"Could not load or build a minimap2 index from {source}") + if (aligner.k, aligner.w) != SHORT_READ_INDEX_K_W: + print( + f"warning: {source} was indexed with k={aligner.k}, w={aligner.w}; " + "short-read indexes (minimap2 -x sr) use k=21, w=11", + file=sys.stderr, + ) + return cls(aligner, mappy) + + def new_buffer(self): + return self._mappy.ThreadBuffer() + + def hits(self, sequence: str, buffer) -> List[GenomeHit]: + return [_genome_hit(hit) for hit in self._aligner.map(sequence, buf=buffer)] + + def fetch(self, contig: str, start: int, end: int) -> str: + """The genome sequence of an interval; empty when the index holds no sequence there.""" + return self._aligner.seq(contig, start, end) or "" + + def window(self, contig: str, start: int, end: int) -> "WindowIndex": + return WindowIndex(self._mappy, contig, start, self.fetch(contig, start, end)) + + +class WindowIndex: + """An index of one genome window with short seeds (``SITE_INDEX_K``, + ``SITE_INDEX_W``), so that a tag too diverged to seed in the genome-wide + search still aligns at a site it belongs to. Each window is an index of + its own, so windows never compete for the aligner's limit on hits. The + mapping options are the short-read preset's, not + ``GENOME_WIDE_MAP_OPTIONS``. Hits come back in genome coordinates.""" + + def __init__(self, mappy_module, contig: str, start: int, sequence: str) -> None: + self._contig, self._start = contig, start + self._aligner = ( + mappy_module.Aligner( + seq=sequence, preset="sr", k=SITE_INDEX_K, w=SITE_INDEX_W, scoring=list(SHORT_READ_SCORING) + ) + if sequence + else None + ) + + def hits(self, sequence: str, buffer=None) -> List[GenomeHit]: + if self._aligner is None: + return [] + return [_genome_hit(hit, self._contig, self._start) for hit in self._aligner.map(sequence, buf=buffer)] + + +def map_sequences( + aligner, sequences: Sequence[str], jobs: int = 1, max_sites: Optional[int] = MAX_SITES_PER_HAPLOTYPE +) -> Dict[str, GenomePlacement]: + """Every sequence's distinct genome sites (``distinct_sites``). + + Worker threads share the index; mappy releases Python's interpreter lock + while it maps, and each batch has a buffer of its own. + """ + + def align_batch(batch: Sequence[str]) -> List[GenomePlacement]: + buffer = aligner.new_buffer() + return [distinct_sites(aligner.hits(sequence, buffer), max_sites) for sequence in batch] + + batches = [sequences[start : start + MAPPING_BATCH] for start in range(0, len(sequences), MAPPING_BATCH)] + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + placements = [placement for found in pool.map(align_batch, batches) for placement in found] + return dict(zip(sequences, placements)) + + +def clone_position(clone_id: str, contigs: Set[str]) -> Tuple[Optional[Tuple[str, int]], Optional[str]]: + """The (contig, 1-based position) a CHROM_POS CloneID names, with None; or None, with why it names none. + + Any CloneID that ends in an underscore and digits is read as CHROM_POS + when what precedes them is a contig of the genome. + """ + match = CLONE_POSITION_RE.fullmatch(clone_id) + if not match: + return None, "no_position" + if match.group(1) not in contigs: + return None, "contig_absent" + return (match.group(1), int(match.group(2))), None + + +def _site_is_at(site: GenomeHit, contig: str, position: int) -> bool: + """Whether a 1-based position lies in a site (0-based, half-open) or within ``CLONE_POSITION_SLACK`` of it.""" + return site.contig == contig and site.start - CLONE_POSITION_SLACK < position <= site.end + CLONE_POSITION_SLACK + + +def place_marker( + clone_id: str, + ref_placement: Optional[GenomePlacement], + contigs: Set[str], + tag_length: int, + use_clone_position: bool = True, + align_ref_tag: Optional[Callable[[str, int, int], Sequence[GenomeHit]]] = None, +) -> MarkerPlacement: + """Locate a marker's tag from its Ref tag's equal-best genome sites and its CloneID position. + + ``ref_placement`` is the Ref tag's genome sites, or None for a marker + without a Ref row. ``tag_length`` sizes the window around a CloneID + position. + + With ``use_clone_position`` the CloneID position is taken to be on this + genome. It picks one of several equal-best sites, and a window around it + stands in for a Ref tag that does not align. If two or more equal-best + sites are at the position (tandem copies), none is picked and every + equal-best site stays the marker's. When no equal-best site is at the + position, ``align_ref_tag(contig, start, end)`` aligns the Ref tag within + a window around it, and an alignment at the position becomes the marker's + site even if the tag aligns better elsewhere: the assembly may carry the + Alt allele at the target and a Ref-like copy elsewhere, or the + genome-wide search may have missed the site. With no such alignment the + marker is unplaced. Either way the disagreement is reported. Without + ``use_clone_position`` (a genome other than the one the CloneIDs refer + to) the position is never read: an unaligned Ref tag leaves the marker + unplaced, and equal-best sites stay multi-copy. + """ + position, no_position_reason = clone_position(clone_id, contigs) if use_clone_position else (None, "ignored") + equal_best = ref_placement.equal_best if ref_placement is not None else () + if position is None: + if not equal_best: + return MarkerPlacement((), "unplaced", 0, no_position_reason) + placed_by = "ref_tag" if len(equal_best) == 1 else "ref_tag_multicopy" + return MarkerPlacement(equal_best, placed_by, len(equal_best), no_position_reason) + contig, clone_base = position + # The genome interval a tag of this length lies in if it contains the CloneID position. + window_start, window_end = max(0, clone_base - 1 - tag_length), clone_base + tag_length + if not equal_best: + return MarkerPlacement((GenomeHit(contig, window_start, window_end, 0, 0),), "clone_id", 0, "fallback") + at_position = [site for site in equal_best if _site_is_at(site, contig, clone_base)] + if len(at_position) == 1: + placed_by = "ref_tag" if len(equal_best) == 1 else "ref_tag+clone_id" + return MarkerPlacement(tuple(at_position), placed_by, len(equal_best), "agree") + if at_position: + return MarkerPlacement(equal_best, "ref_tag_multicopy", len(equal_best), "agree") + realigned = () + if align_ref_tag is not None: + realigned = align_ref_tag(contig, max(0, window_start - SITE_FLANK), window_end + SITE_FLANK) + realigned_at_position = [hit for hit in realigned if _site_is_at(hit, contig, clone_base)] + if realigned_at_position: + best = max(realigned_at_position, key=lambda hit: hit.score) + return MarkerPlacement((best,), "clone_id_site", len(equal_best), "disagree") + return MarkerPlacement((), "unplaced", len(equal_best), "disagree") + + +def score_at_sites( + aligner, markers: Mapping[str, MarkerPlacement], haplotypes: Iterable[Tuple[str, str]], jobs: int = 1 +) -> Dict[Tuple[str, str], int]: + """Each (CloneID, sequence) pair's best score within its own marker's sites. + + A site is searched with ``SITE_FLANK`` genome bases either side of it. + Every placed marker's sites are indexed on their own with short seeds + (``WindowIndex``), so an allele of the marker that carries several SNPs, + which the genome-wide search misses or aligns only in part at the + marker's site, is still scored there. Markers that share a site do not + compete for the aligner's limit on hits. Pairs that do not align at + their marker's sites, and pairs of unplaced markers, are left out. + """ + sequences_by_marker: Dict[str, Set[str]] = defaultdict(set) + for clone_id, sequence in haplotypes: + if markers[clone_id].sites: + sequences_by_marker[clone_id].add(sequence) + + def score_marker(clone_id: str) -> Dict[Tuple[str, str], int]: + windows = [ + aligner.window(site.contig, max(0, site.start - SITE_FLANK), site.end + SITE_FLANK) + for site in markers[clone_id].sites + ] + buffer = aligner.new_buffer() + best_scores = {} + for sequence in sequences_by_marker[clone_id]: + scores = [hit.score for window in windows for hit in window.hits(sequence, buffer)] + if scores: + best_scores[(clone_id, sequence)] = max(scores) + return best_scores + + site_scores: Dict[Tuple[str, str], int] = {} + with concurrent.futures.ThreadPoolExecutor(max_workers=jobs) as pool: + for best_scores in pool.map(score_marker, list(sequences_by_marker)): + site_scores.update(best_scores) + return site_scores + + +def genome_label(placement: GenomePlacement, marker: MarkerPlacement, site_score: Optional[int] = None) -> GenomeLabel: + """Label a haplotype by its best score at its marker's own site against its best score anywhere else. + + ``on_target``: the marker's site scores strictly best. ``paralog``: + somewhere else scores strictly better (or the haplotype aligns only + elsewhere). ``ambiguous``: a tie between the marker's site and another + site, or a marker whose own Ref tag is multi-copy and unresolved. + ``unmapped``: no alignment. ``unplaced``: the marker itself could not be + located, so the haplotype cannot be judged. + + ``placement`` is the haplotype's sites from the genome-wide search and + ``marker`` its marker's placement. ``site_score`` is the haplotype's + score in the realignment at the marker's site (``score_at_sites``), or + None when it did not align there. The target score is the higher of it + and the genome-wide hit at the site, so the label does not depend on + which search found the site. + """ + hits_at_marker = [hit for hit in placement.sites if any(_same_locus(hit, site) for site in marker.sites)] + hits_elsewhere = [hit for hit in placement.sites if hit not in hits_at_marker] + off_target_score = hits_elsewhere[0].score if hits_elsewhere else None + off_target_sites = sum(hit.score == off_target_score for hit in hits_elsewhere) + off_target_hit = hits_elsewhere[0] if hits_elsewhere else None + if not marker.sites: + return GenomeLabel("unplaced", None, ".", off_target_score, off_target_sites, off_target_hit) + if site_score is not None and (not hits_at_marker or site_score > hits_at_marker[0].score): + target_score, target_from = site_score, "site" + elif hits_at_marker: + target_score, target_from = hits_at_marker[0].score, "genome" + else: + target_score, target_from = None, "." + if target_score is None and off_target_score is None: + label = "unmapped" + elif target_score is None or (off_target_score is not None and off_target_score > target_score): + label = "paralog" + elif off_target_score == target_score or len(marker.sites) > 1: + label = "ambiguous" + else: + label = "on_target" + return GenomeLabel(label, target_score, target_from, off_target_score, off_target_sites, off_target_hit) + + +def _preamble_header_and_rows(handle, path: Path): + """(preamble rows, header row, reader positioned at the first data row) of an open MADC.""" + reader = csv.reader(handle) + preamble = [] + for row in reader: + if is_madc_header(row): + return preamble, row, reader + preamble.append(row) + raise MadcError(f"Could not find an AlleleID header row in MADC file: {path}") + + +def _haplotype_rows(reader, header: Sequence[str], path: Path): + """The haplotype rows of a MADC, each as (row, AlleleID, CloneID, sequence in upper case). + + A row with an empty AlleleID, or too short to hold the three identity + columns, is not a haplotype row and is passed over. + """ + allele_index, clone_index, sequence_index = madc_identity_columns(header, path) + width = max(allele_index, clone_index, sequence_index) + 1 + for row in reader: + if len(row) < width or not row[allele_index].strip(): + continue + yield row, row[allele_index].strip(), row[clone_index].strip(), row[sequence_index].strip().upper() + + +def _label_column_index(header: Sequence[str], madc_path: Path) -> int: + """The column that carries the flag: a GenomeLabel column from an earlier run, or PICRef.""" + stripped = [column.strip() for column in header] + for name in (GENOME_LABEL_COLUMN, REPLACED_STATISTICS_COLUMN): + if name in stripped: + return stripped.index(name) + raise MadcError( + f"{madc_path} has no {REPLACED_STATISTICS_COLUMN} column to carry the flag; use drop mode, " + "or read the labels sidecar" + ) + + +def check_madc_header(madc_path: Path, flagging: bool) -> None: + """Stop with an error when the MADC cannot be filtered as asked. + + That is a MADC without a header row or without its identity columns, or, + when rows are to be flagged, without a column to carry the flag. + """ + with open_text(madc_path, "rt") as handle: + _, header, _ = _preamble_header_and_rows(handle, madc_path) + madc_identity_columns(header, madc_path) + if flagging: + _label_column_index(header, madc_path) + + +def _read_haplotypes(madc_path: Path): + """Pass 1 over the MADC: its distinct haplotypes, and each marker's Ref tag and tag length. + + Returns the header row and three dictionaries, each in the order of first + appearance. ``haplotypes`` maps (CloneID, sequence as written) to the + sequence that is aligned, which is the sequence without gap characters. + ``ref_tags`` maps a CloneID to its first Ref row's sequence without gaps, + and ``tag_lengths`` to the length of its first row as written. + """ + haplotypes: Dict[Tuple[str, str], str] = {} + ref_tags: Dict[str, str] = {} + tag_lengths: Dict[str, int] = {} + with open_text(madc_path, "rt") as handle: + _, header, reader = _preamble_header_and_rows(handle, madc_path) + for _, allele_id, clone_id, sequence in _haplotype_rows(reader, header, madc_path): + ungapped = sequence.replace("-", "") + haplotypes[(clone_id, sequence)] = ungapped + tag_lengths.setdefault(clone_id, len(sequence)) + if clone_id not in ref_tags and allele_type(allele_id) == "Ref": + ref_tags[clone_id] = ungapped + return header, haplotypes, ref_tags, tag_lengths + + +def _place_markers( + aligner, ref_tags: Mapping[str, str], tag_lengths: Mapping[str, int], use_clone_position: bool, jobs: int +) -> Dict[str, MarkerPlacement]: + """Every marker's placement (``place_marker``), from the genome sites of its Ref tag.""" + # Ref tags keep every equal-best site, so a capped list cannot hide the one the CloneID names. + ref_placements = map_sequences(aligner, sorted(set(ref_tags.values())), jobs, max_sites=None) + markers: Dict[str, MarkerPlacement] = {} + for clone_id, tag_length in tag_lengths.items(): + ref_tag = ref_tags.get(clone_id) # None for a marker without a Ref row, which place_marker never aligns + + def align_ref_tag(contig: str, start: int, end: int, ref_tag=ref_tag) -> List[GenomeHit]: + return aligner.window(contig, start, end).hits(ref_tag) + + markers[clone_id] = place_marker( + clone_id, ref_placements.get(ref_tag), aligner.contigs, tag_length, use_clone_position, align_ref_tag + ) + return markers + + +def _format_site(site: GenomeHit) -> str: + """A site as contig:start-end(strand), 1-based and inclusive, as the two sidecars show it.""" + strand = {1: "+", -1: "-"}.get(site.strand, ".") + return f"{site.contig}:{site.start + 1}-{site.end}({strand})" + + +def _dot_if_none(value) -> object: + return "." if value is None else value + + +def _write_markers_sidecar(markers_path: Path, markers: Mapping[str, MarkerPlacement]) -> None: + markers_path.parent.mkdir(parents=True, exist_ok=True) + with markers_path.open("w", newline="") as handle: + writer = csv.writer(handle, lineterminator="\n") + writer.writerow(MARKERS_SIDECAR_COLUMNS) + for clone_id, marker in markers.items(): + sites = ";".join(_format_site(site) for site in marker.sites) or "." + writer.writerow([clone_id, marker.placed_by, marker.ref_tag_site_count, marker.clone_id_check, sites]) + + +class _RowTallies(NamedTuple): + """Rows and reads counted while the table is written, in total and by label, outcome and allele category.""" + + totals: Dict[str, Dict[str, int]] + by_label: Dict[str, Dict[str, int]] + by_outcome: Dict[str, Dict[str, int]] + by_category: Dict[str, Dict[str, Dict[str, int]]] + overflow: CountOverflowCheck + + +def _write_filtered_table( + madc_path: Path, + output: Path, + labels_path: Path, + labels: Mapping[Tuple[str, str], GenomeLabel], + actions: Mapping[str, str], + label_index: Optional[int], + provenance: str, +) -> _RowTallies: + """Pass 2 over the MADC: write the rows that are kept, and every row's label to the labels sidecar. + + ``actions`` gives what was asked for ``paralog`` and ``ambiguous`` rows + (``drop``, ``flag`` or ``keep``); rows with any other label are kept. + What is done with a row is its outcome, the sidecar's Action column: + ``kept``, ``flagged``, ``dropped``, or ``protected`` for a canonical Ref + or Alt row that would have been dropped and is kept. With ``label_index`` + every row written carries its label in that column, whatever its outcome. + """ + + def tally(): + return defaultdict(lambda: {"rows": 0, "reads": 0}) + + by_label, by_outcome = tally(), tally() + by_category: Dict[str, Dict[str, Dict[str, int]]] = defaultdict(tally) + overflow = CountOverflowCheck() + totals = {"input": {"rows": 0, "reads": 0}, "output": {"rows": 0, "reads": 0}} + output.parent.mkdir(parents=True, exist_ok=True) + labels_path.parent.mkdir(parents=True, exist_ok=True) + with open_text(madc_path, "rt") as handle, open_text(output, "wt") as out_handle, labels_path.open( + "w", newline="" + ) as label_handle: + preamble, header, reader = _preamble_header_and_rows(handle, madc_path) + writer = csv.writer(out_handle, lineterminator="\n") + label_writer = csv.writer(label_handle, lineterminator="\n") + label_writer.writerow(LABELS_SIDECAR_COLUMNS) + if provenance and preamble and preamble[0] and preamble[0][0].startswith("* MADCATS"): + preamble[0] = [f"{preamble[0][0]} | {provenance}"] + preamble[0][1:] + writer.writerows(preamble) + if label_index is not None: + header[label_index] = GENOME_LABEL_COLUMN + writer.writerow(header) + sample_start = madc_sample_start(header) + for row, allele_id, clone_id, sequence in _haplotype_rows(reader, header, madc_path): + haplotype_label = labels[(clone_id, sequence)] + category = allele_type(allele_id) + requested = actions.get(haplotype_label.label, "keep") + if requested == "drop": + outcome = "protected" if category in ("Ref", "Alt") else "dropped" + else: + outcome = "flagged" if requested == "flag" else "kept" + counts = madc_read_counts(row[sample_start:], madc_path) + overflow.add(clone_id, counts) + reads = sum(counts) + label = haplotype_label.label + for counted in (totals["input"], by_label[label], by_outcome[outcome], by_category[category][label]): + counted["rows"] += 1 + counted["reads"] += reads + if outcome != "dropped": + if label_index is not None: + row = row + [""] * max(0, label_index + 1 - len(row)) + row[label_index] = label + writer.writerow(row) + totals["output"]["rows"] += 1 + totals["output"]["reads"] += reads + off_target_hit = haplotype_label.off_target_hit + label_writer.writerow([ + clone_id, allele_id, sequence, label, outcome, + _dot_if_none(haplotype_label.target_score), haplotype_label.target_from, + _dot_if_none(haplotype_label.off_target_score), haplotype_label.off_target_sites, + "." if off_target_hit is None else _format_site(off_target_hit), + ]) + return _RowTallies(totals, by_label, by_outcome, by_category, overflow) + + +def filter_paralogs( + madc_path: Path, + output: Path, + aligner, + labels_path: Path, + markers_path: Path, + paralog_action: str = "drop", + ambiguous_action: str = "drop", + jobs: int = 1, + provenance: str = "", + clone_positions: str = "use", +) -> Dict[str, object]: + """Label every MADC haplotype by where the genome places it; drop or flag paralogous rows. + + Pass 1 reads only row identities (``_read_haplotypes``). Every distinct + haplotype is aligned to the genome once; each marker is located from its + Ref row's tag, all of whose equal-best sites are kept (``place_marker``); + every haplotype is realigned to its own marker's sites + (``score_at_sites``) and labelled by ``genome_label``. Pass 2 streams the + table again and writes the kept rows unchanged + (``_write_filtered_table``), so a vendor MADC keeps its preamble, + statistics and column layout, and a HapApp fixed-allele-ID MADC keeps its + Code_version column. Canonical Ref and Alt rows are never dropped, since + downstream dosage tools need both designed alleles; they are reported as + ``protected`` instead. In flag mode the PICRef column becomes + ``GenomeLabel`` on every row. The labels sidecar has one line per + haplotype row, dropped rows included. ``clone_positions="use"`` takes + CloneID coordinates to be on this genome; ``"ignore"`` keeps them out of + marker placement, for a genome other than the one they refer to. + + Returns the summary that goes into the QC JSON. + """ + actions = {"paralog": paralog_action, "ambiguous": ambiguous_action} + header, haplotypes, ref_tags, tag_lengths = _read_haplotypes(madc_path) + label_index = _label_column_index(header, madc_path) if "flag" in actions.values() else None + + sequences = sorted(set(haplotypes.values())) + print(f"Aligning {len(sequences):,} distinct haplotype sequences on {jobs} thread(s)", file=sys.stderr) + started = time.time() + placements = map_sequences(aligner, sequences, jobs) + markers = _place_markers(aligner, ref_tags, tag_lengths, clone_positions == "use", jobs) + # Realign every haplotype at its own marker's sites, and label it by the better of the two scores there. + aligned_pairs = {(clone_id, ungapped) for (clone_id, _), ungapped in haplotypes.items()} + site_scores = score_at_sites(aligner, markers, aligned_pairs, jobs) + labels = { + (clone_id, sequence): genome_label( + placements[ungapped], markers[clone_id], site_scores.get((clone_id, ungapped)) + ) + for (clone_id, sequence), ungapped in haplotypes.items() + } + alignment_seconds = round(time.time() - started, 1) + + _write_markers_sidecar(markers_path, markers) + try: + tallies = _write_filtered_table(madc_path, output, labels_path, labels, actions, label_index, provenance) + except BaseException: + # A run that fails part of the way through leaves no partial files behind. + for partial in (output, labels_path, markers_path): + partial.unlink(missing_ok=True) + raise + + warning = tallies.overflow.warning(madc_path) + if warning: + print(warning, file=sys.stderr) + sources = Counter(marker.placed_by for marker in markers.values()) + checks = Counter(marker.clone_id_check for marker in markers.values()) + checked = checks["agree"] + checks["disagree"] + if checked and checks["disagree"] > CLONE_DISAGREEMENT_WARNING_SHARE * checked: + print( + f"warning: CloneID positions disagree with the Ref tag's best genome sites for {checks['disagree']:,} " + f"of {checked:,} markers, so they may refer to another assembly. Those markers were placed at their " + "CloneID position, or left unplaced where the Ref tag does not align there. If the positions refer " + "to another assembly, rerun with --clone-positions ignore", + file=sys.stderr, + ) + if markers and not sources.keys() - {"unplaced"}: + print("warning: no marker could be placed on the genome; every row was kept", file=sys.stderr) + + def plain(tally: Mapping[str, Dict[str, int]]) -> Dict[str, Dict[str, int]]: + return {key: dict(counts) for key, counts in tally.items()} + + return { + "markers": { + "total": len(markers), + "placement": dict(sources), + "clone_id_check": dict(checks), + "multicopy_ref_tags": [clone_id for clone_id, marker in markers.items() if marker.ref_tag_site_count > 1], + "clone_id_disagreements": [ + clone_id for clone_id, marker in markers.items() if marker.clone_id_check == "disagree" + ], + "unplaced": [clone_id for clone_id, marker in markers.items() if marker.placed_by == "unplaced"], + }, + "haplotypes": { + "distinct": len(haplotypes), + "distinct_sequences": len(sequences), + "labels": dict(Counter(result.label for result in labels.values())), + "realigned_at_site": { + "haplotypes": sum(bool(markers[clone_id].sites) for clone_id, _ in haplotypes), + "found_at_site": sum(pair in site_scores for pair in + ((clone_id, ungapped) for (clone_id, _), ungapped in haplotypes.items())), + "target_from_site": sum(result.target_from == "site" for result in labels.values()), + }, + "alignment_seconds": alignment_seconds, + }, + "rows": { + **tallies.totals, + "by_label": plain(tallies.by_label), + "by_outcome": plain(tallies.by_outcome), + "by_category": {category: plain(by_label) for category, by_label in tallies.by_category.items()}, + }, + "genome_label_column": GENOME_LABEL_COLUMN if label_index is not None else None, + "count_overflow": tallies.overflow.summary(), + } + + +def run_filter_paralogs(args: argparse.Namespace) -> int: + """Clean a finished MADC with a reference genome (see ``filter_paralogs``).""" + if not args.genome and not args.genome_index: + raise MadcError("filter-paralogs needs --genome, --genome-index, or both") + madc = Path(args.madc) + output = Path(args.output) + if not madc.is_file(): + raise MadcError(f"MADC not found: {madc}") + if output.resolve() == madc.resolve(): + raise MadcError("--output must be a new file, not the input MADC") + genome = Path(args.genome) if args.genome else None + index = Path(args.genome_index) if args.genome_index else None + # A MADC that cannot be filtered as asked is refused before the index is loaded, which can take minutes. + check_madc_header(madc, flagging="flag" in (args.paralogs, args.ambiguous)) + started = time.time() + aligner = GenomeAligner.open(genome, index, args.jobs) + labels_path = output.with_suffix(output.suffix + ".genome_labels.csv") + markers_path = output.with_suffix(output.suffix + ".genome_markers.csv") + provenance = ( + f"filter-paralogs v{__version__} paralogs={args.paralogs} ambiguous={args.ambiguous} " + f"clone_positions={args.clone_positions}" + ) + summary = filter_paralogs( + madc, output, aligner, labels_path, markers_path, + paralog_action=args.paralogs, ambiguous_action=args.ambiguous, jobs=args.jobs, provenance=provenance, + clone_positions=args.clone_positions, + ) + qc_path = Path(args.qc_output) if args.qc_output else output.with_suffix(output.suffix + ".qc.json") + qc = { + "pipeline": "MADCATS", + "command": "filter-paralogs", + "version": __version__, + "created_utc": dt.datetime.now(dt.timezone.utc).isoformat(), + "inputs": { + "madc": str(madc.resolve()), + "genome": str(genome.resolve()) if genome else None, + "genome_index": str(index.resolve()) if index else None, + }, + "parameters": { + "paralogs": args.paralogs, "ambiguous": args.ambiguous, "clone_positions": args.clone_positions, + "jobs": args.jobs, + }, + "aligner": aligner.description, + "outputs": {"madc": str(output.resolve()), "labels": str(labels_path), "markers": str(markers_path)}, + "elapsed_seconds": round(time.time() - started, 1), + **summary, + } + _write_json(qc_path, qc) + rows = summary["rows"] + dropped_reads = rows["input"]["reads"] - rows["output"]["reads"] + dropped_share = dropped_reads / rows["input"]["reads"] if rows["input"]["reads"] else 0.0 + print( + f"Kept {rows['output']['rows']:,} of {rows['input']['rows']:,} rows; " + f"dropped {dropped_reads:,} reads ({dropped_share:.1%})", + file=sys.stderr, + ) + print( + f"Wrote {output}, its labels {labels_path}, its markers {markers_path}, and QC to {qc_path}", file=sys.stderr + ) + return 0 + + +def add_filter_paralogs_command(subparsers) -> None: + filtering = subparsers.add_parser( + "filter-paralogs", + help="drop or flag MADC rows that a reference genome places at another locus (experimental, requires mappy)", + description=( + "Drop or flag MADC rows that align better to another locus in a reference genome, for panels where " + "co-amplified paralogs inflate heterozygosity. Places each marker using its Ref tag and (for " + "CHROM_POS CloneIDs) its expected genomic coordinate, then aligns every distinct haplotype and labels " + "it on_target, paralog (scores higher elsewhere), or ambiguous (ties between target and off-target " + "sites). Experimental in 0.14.0. Requires the mappy aligner: pip install 'madcats[genome]'." + ), + ) + filtering.add_argument( + "--madc", + required=True, + help=( + "MADC to filter (plain or gzipped), from generate, a vendor DArT delivery (with or without starred " + "preamble), or HapApp's fixed-allele-ID format" + ), + ) + filtering.add_argument( + "--genome", + help=( + "reference genome FASTA (plain or gzipped) containing a single chromosome set (one haplotype copy " + "per locus). Not needed when --genome-index already exists" + ), + ) + filtering.add_argument( + "--genome-index", + help=( + "single-part minimap2 index (.mmi) built with -x sr. Loaded if present, otherwise built from " + "--genome and saved for reuse" + ), + ) + filtering.add_argument( + "--clone-positions", + choices=("use", "ignore"), + default="use", + help=( + "handling of CHROM_POS CloneIDs: use treats them as coordinates on this genome (leaving markers " + "unplaced if their Ref tag aligns only elsewhere), while ignore locates markers by Ref tag alone " + "for CloneIDs from another assembly (default: use)" + ), + ) + filtering.add_argument( + "--output", + required=True, + help=( + "filtered MADC CSV to write. Also writes OUTPUT.genome_labels.csv (each row's label, scores, and " + "action) and OUTPUT.genome_markers.csv (each marker's placed site)" + ), + ) + filtering.add_argument( + "--paralogs", + choices=("drop", "flag"), + default="drop", + help=( + "drop paralog rows, or flag them by keeping them and writing every row's label in a GenomeLabel " + "column replacing PICRef. Canonical Ref and Alt rows are always kept (default: drop)" + ), + ) + filtering.add_argument( + "--ambiguous", + choices=("drop", "flag", "keep"), + default="drop", + help=( + "handling of ambiguous rows (including all rows of a marker whose Ref tag has multiple equal-best " + "sites): drop, flag (same as --paralogs flag), or keep (default: drop)" + ), + ) + filtering.add_argument("--qc-output", help="QC JSON (default: OUTPUT.qc.json)") + filtering.add_argument( + "--jobs", type=positive_int, default=_default_jobs(), help="alignment threads (default: up to 4)" + ) + filtering.set_defaults(func=run_filter_paralogs) diff --git a/pyproject.toml b/pyproject.toml index 0a4a751..9ab6d94 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,11 @@ classifiers = [ "Topic :: Scientific/Engineering :: Bio-Informatics", ] +[project.optional-dependencies] +# filter-paralogs aligns haplotypes to a reference genome with minimap2; every other command +# needs only the standard library. +genome = ["mappy>=2.24"] + [project.urls] Homepage = "https://github.com/Breeding-Insight/MADCATS" Documentation = "https://madcats.readthedocs.io" @@ -48,7 +53,7 @@ Changelog = "https://madcats.readthedocs.io/en/latest/development/changelog.html madcats = "madcats:main" [tool.setuptools] -py-modules = ["madcats"] +py-modules = ["madcats", "madcats_paralogs"] [tool.setuptools.dynamic] version = { attr = "madcats.__version__" } diff --git a/tests/fixtures/generate_v013/README.md b/tests/fixtures/generate_v013/README.md new file mode 100644 index 0000000..5d4ec73 --- /dev/null +++ b/tests/fixtures/generate_v013/README.md @@ -0,0 +1,23 @@ +# v0.13.0 generation baseline + +These tables were generated by `madcats.py` from tag `v0.13.0` +(commit `302541a215f9105901db73fbb980a7d70e4dde56`), using the checked-in `examples/madcats-demo` data. +They are frozen outputs, not regenerated by the implementation under test. + +Commands, with the v0.13.0 script saved as `madcats_v013.py`: + +```bash +python3 madcats_v013.py design --primers examples/madcats-demo/primers.csv \ + --probe-design examples/madcats-demo/probe_design.tsv --output tags.csv +python3 madcats_v013.py generate --fastq-dir examples/madcats-demo/fastq \ + --reference-tags tags.csv --sample-lookup examples/madcats-demo/sample_names.csv \ + --jobs 1 --gapped-rescue on --output gapped_on.csv +python3 madcats_v013.py generate --fastq-dir examples/madcats-demo/fastq \ + --reference-tags tags.csv --sample-lookup examples/madcats-demo/sample_names.csv \ + --jobs 1 --gapped-rescue off --output gapped_off.csv +``` + +The comparison includes every row, category, sequence, annotation and per-sample count. +No vendor preamble was requested, so version/provenance differences do not affect the files. +The example has no tile families; tiled panels need `--tile-groups off` for the old assignment +behaviour. This is regression coverage of one simulated panel, not validation of every real panel. diff --git a/tests/fixtures/generate_v013/gapped_off.csv b/tests/fixtures/generate_v013/gapped_off.csv new file mode 100644 index 0000000..5702449 --- /dev/null +++ b/tests/fixtures/generate_v013/gapped_off.csv @@ -0,0 +1,19 @@ +AlleleID,CloneID,AlleleSequence,ClusterConsensusSequence,CallRate,OneRatioRef,OneRatioSnp,FreqHomRef,FreqHomSnp,FreqHets,PICRef,Variants,MarkerType,AvgCountRef,AvgCountSnp,RatioAvgCountRefAvgCountSnp,Line_01,Line_02,Line_03,Line_04,Line_05,Line_06,Line_07,Line_08,Line_09,Line_10,Line_11,Line_12 +Chr01_000412883|Ref,Chr01_000412883,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTGTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTGTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,1,.,.,.,.,.,.,.,.,46.777778,45.666667,.,76,35,0,25,64,37,0,0,43,66,42,33 +Chr01_000412883|Alt,Chr01_000412883,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTCTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTCTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,1,.,.,.,.,.,.,34:G>C,snp,46.777778,45.666667,.,0,35,76,36,0,27,69,68,26,0,31,43 +Chr02_001257730|Ref,Chr02_001257730,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,1,.,.,.,.,.,.,.,.,40.125,46.25,.,30,0,24,40,26,0,0,25,66,0,29,81 +Chr02_001257730|Alt,Chr02_001257730,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATCTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATCTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,1,.,.,.,.,.,.,48:G>C,snp,40.125,46.25,.,0,75,31,0,45,68,35,41,0,35,40,0 +Chr02_001257730|RefMatch,Chr02_001257730,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCTAGCAGGAGGCGGAA,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,0,.,.,.,.,.,.,67:A>T,snp,37.5,37.5,.,39,0,0,43,0,0,26,0,0,42,0,0 +Chr03_000086214|Ref,Chr03_000086214,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCTCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCTCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,1,.,.,.,.,.,.,.,.,49.777778,46.888889,.,0,33,73,38,0,0,40,79,45,33,64,43 +Chr03_000086214|Alt,Chr03_000086214,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCCCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCCCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,1,.,.,.,.,.,.,41:T>C,snp,49.777778,46.888889,.,71,31,0,39,71,65,29,0,39,37,0,40 +Chr04_002318006|Ref,Chr04_002318006,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACAACGCTCCGATCAAGTACCTGGGGT,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACAACGCTCCGATCAAGTACCTGGGGT,1,.,.,.,.,.,.,.,.,38.444444,42,.,34,67,45,0,0,27,37,38,38,29,31,0 +Chr04_002318006|Alt,Chr04_002318006,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACTACGCTCCGATCAAGTACCTGGGGT,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACTACGCTCCGATCAAGTACCTGGGGT,1,.,.,.,.,.,.,57:A>T,snp,38.444444,42,.,0,0,25,28,76,38,0,25,25,0,37,82 +Chr04_002318006|AltMatch,Chr04_002318006,TCTGGAGGTGCGCGCAGGTTTAGTTATCTGGATCAGGCGTTTGAACAGGACTGGACTACGCTCCGATCAAGTACCTGGGGT,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACAACGCTCCGATCAAGTACCTGGGGT,0,.,.,.,.,.,.,25:G>T;57:A>T,snp,30.5,30.5,.,28,0,0,25,0,0,35,0,0,34,0,0 +Chr05_000970341|Ref,Chr05_000970341,CGGCTCCACCTTAGCGATTCGCATAAAGGGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,CGGCTCCACCTTAGCGATTCGCATAAAGGGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,1,.,.,.,.,.,.,.,.,48.333333,39.636364,.,78,38,0,0,26,63,41,38,75,39,0,37 +Chr05_000970341|Alt,Chr05_000970341,CGGCTCCACCTTAGCGATTCGCATAAAGCGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,CGGCTCCACCTTAGCGATTCGCATAAAGCGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,1,.,.,.,.,.,.,29:G>C,snp,48.333333,39.636364,.,1,37,83,65,41,0,38,28,1,37,70,35 +Chr06_001644492|Ref,Chr06_001644492,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGCAGATGACCTAGCTTACAATTATCCCCCGT,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGCAGATGACCTAGCTTACAATTATCCCCCGT,1,.,.,.,.,.,.,.,.,50.875,44.142857,.,26,0,0,0,85,42,40,70,44,0,27,73 +Chr06_001644492|Alt,Chr06_001644492,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGGAGATGACCTAGCTTACAATTATCCCCCGT,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGGAGATGACCTAGCTTACAATTATCCCCCGT,1,.,.,.,.,.,.,52:C>G,snp,50.875,44.142857,.,0,66,77,32,0,37,0,0,32,29,36,0 +Chr07_000203517|Ref,Chr07_000203517,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATTTGCTGAACCCTTTCTCGA,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATTTGCTGAACCCTTTCTCGA,1,.,.,.,.,.,.,.,.,37.5,44.222222,.,1,0,30,58,32,39,51,27,0,29,79,29 +Chr07_000203517|Alt,Chr07_000203517,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATCTGCTGAACCCTTTCTCGA,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATCTGCTGAACCCTTTCTCGA,1,.,.,.,.,.,.,63:T>C,snp,37.5,44.222222,.,70,65,35,0,25,41,0,28,59,43,0,32 +Chr08_001105968|Ref,Chr08_001105968,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAGTTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAGTTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,1,.,.,.,.,.,.,.,.,68.75,1,.,59,74,60,64,75,69,77,52,73,79,62,81 +Chr08_001105968|Alt,Chr08_001105968,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAATTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAATTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,1,.,.,.,.,.,.,45:G>A,snp,68.75,1,.,0,0,0,0,0,0,0,0,1,0,0,0 diff --git a/tests/fixtures/generate_v013/gapped_on.csv b/tests/fixtures/generate_v013/gapped_on.csv new file mode 100644 index 0000000..cf51e91 --- /dev/null +++ b/tests/fixtures/generate_v013/gapped_on.csv @@ -0,0 +1,20 @@ +AlleleID,CloneID,AlleleSequence,ClusterConsensusSequence,CallRate,OneRatioRef,OneRatioSnp,FreqHomRef,FreqHomSnp,FreqHets,PICRef,Variants,MarkerType,AvgCountRef,AvgCountSnp,RatioAvgCountRefAvgCountSnp,Line_01,Line_02,Line_03,Line_04,Line_05,Line_06,Line_07,Line_08,Line_09,Line_10,Line_11,Line_12 +Chr01_000412883|Ref,Chr01_000412883,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTGTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTGTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,1,.,.,.,.,.,.,.,.,46.777778,45.666667,.,76,35,0,25,64,37,0,0,43,66,42,33 +Chr01_000412883|Alt,Chr01_000412883,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTCTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,AGATATGCTGGGTAGAGGTCGAGGTTATTATTTCTTACCAATTCTCATTGTGTTTCGGAACTTGCGTTTTAGGTATGTCTT,1,.,.,.,.,.,.,34:G>C,snp,46.777778,45.666667,.,0,35,76,36,0,27,69,68,26,0,31,43 +Chr02_001257730|Ref,Chr02_001257730,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,1,.,.,.,.,.,.,.,.,40.125,46.25,.,30,0,24,40,26,0,0,25,66,0,29,81 +Chr02_001257730|Alt,Chr02_001257730,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATCTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATCTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,1,.,.,.,.,.,.,48:G>C,snp,40.125,46.25,.,0,75,31,0,45,68,35,41,0,35,40,0 +Chr02_001257730|RefMatch,Chr02_001257730,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCTAGCAGGAGGCGGAA,GTCATACCAATCTACCCCCTGTTATGCGCGTTTGTCGTTAGACCAATGTCAGCGCAGCGGCAGATCAAGCAGGAGGCGGAA,0,.,.,.,.,.,.,67:A>T,snp,37.5,37.5,.,39,0,0,43,0,0,26,0,0,42,0,0 +Chr03_000086214|Ref,Chr03_000086214,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCTCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCTCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,1,.,.,.,.,.,.,.,.,49.777778,46.888889,.,0,33,73,38,0,0,40,79,45,33,64,43 +Chr03_000086214|Alt,Chr03_000086214,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCCCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,ATGCCAAGTTGGCACAGGGAACTACCTGCGGCGGTTTGCCCCTAGTACAGGGCAACGATTCAACTGGGACCGGGGCTCATT,1,.,.,.,.,.,.,41:T>C,snp,49.777778,46.888889,.,71,31,0,39,71,65,29,0,39,37,0,40 +Chr04_002318006|Ref,Chr04_002318006,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACAACGCTCCGATCAAGTACCTGGGGT,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACAACGCTCCGATCAAGTACCTGGGGT,1,.,.,.,.,.,.,.,.,38.444444,42,.,34,67,45,0,0,27,37,38,38,29,31,0 +Chr04_002318006|Alt,Chr04_002318006,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACTACGCTCCGATCAAGTACCTGGGGT,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACTACGCTCCGATCAAGTACCTGGGGT,1,.,.,.,.,.,.,57:A>T,snp,38.444444,42,.,0,0,25,28,76,38,0,25,25,0,37,82 +Chr04_002318006|AltMatch,Chr04_002318006,TCTGGAGGTGCGCGCAGGTTTAGTTATCTGGATCAGGCGTTTGAACAGGACTGGACTACGCTCCGATCAAGTACCTGGGGT,TCTGGAGGTGCGCGCAGGTTTAGTGATCTGGATCAGGCGTTTGAACAGGACTGGACAACGCTCCGATCAAGTACCTGGGGT,0,.,.,.,.,.,.,25:G>T;57:A>T,snp,30.5,30.5,.,28,0,0,25,0,0,35,0,0,34,0,0 +Chr05_000970341|Ref,Chr05_000970341,CGGCTCCACCTTAGCGATTCGCATAAAGGGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,CGGCTCCACCTTAGCGATTCGCATAAAGGGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,1,.,.,.,.,.,.,.,.,48.333333,39.636364,.,78,38,0,0,26,63,41,38,75,39,0,37 +Chr05_000970341|Alt,Chr05_000970341,CGGCTCCACCTTAGCGATTCGCATAAAGCGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,CGGCTCCACCTTAGCGATTCGCATAAAGCGACCATTCCCCTCGCTTTGCGTTACCAAGCACCTCTACGGGTATTGGTCACC,1,.,.,.,.,.,.,29:G>C,snp,48.333333,39.636364,.,1,37,83,65,41,0,38,28,1,37,70,35 +Chr06_001644492|Ref,Chr06_001644492,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGCAGATGACCTAGCTTACAATTATCCCCCGT,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGCAGATGACCTAGCTTACAATTATCCCCCGT,1,.,.,.,.,.,.,.,.,50.875,44.142857,.,26,0,0,0,85,42,40,70,44,0,27,73 +Chr06_001644492|Alt,Chr06_001644492,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGGAGATGACCTAGCTTACAATTATCCCCCGT,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGGAGATGACCTAGCTTACAATTATCCCCCGT,1,.,.,.,.,.,.,52:C>G,snp,50.875,44.142857,.,0,66,77,32,0,37,0,0,32,29,36,0 +Chr06_001644492|RefMatch,Chr06_001644492,CTATCGCGGTAGCAGCACTTAATTACCAGCCGGAGCACATAGTACTAGACAGCAGATGACCTAGCTTACAATTATCCCCCG,CTATCGCGGTAGCAGCACTTAATTACCAGCGGAGCACATAGTACTAGACAGCAGATGACCTAGCTTACAATTATCCCCCGT,0,.,.,.,.,.,.,29:G>GC;clip=1,indel,32,32,.,30,0,0,32,0,0,25,0,0,41,0,0 +Chr07_000203517|Ref,Chr07_000203517,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATTTGCTGAACCCTTTCTCGA,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATTTGCTGAACCCTTTCTCGA,1,.,.,.,.,.,.,.,.,37.5,44.222222,.,1,0,30,58,32,39,51,27,0,29,79,29 +Chr07_000203517|Alt,Chr07_000203517,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATCTGCTGAACCCTTTCTCGA,GTATGTTGGTTTGGCAACCGTCGCACTCGTCGTGGTCCGACGCTCTTTAGAGGTCGGGTCATCTGCTGAACCCTTTCTCGA,1,.,.,.,.,.,.,63:T>C,snp,37.5,44.222222,.,70,65,35,0,25,41,0,28,59,43,0,32 +Chr08_001105968|Ref,Chr08_001105968,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAGTTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAGTTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,1,.,.,.,.,.,.,.,.,68.75,1,.,59,74,60,64,75,69,77,52,73,79,62,81 +Chr08_001105968|Alt,Chr08_001105968,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAATTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,CGGTACGATAGGTGCCTGAGTGTGCTCGGGGACACGGAGTTTTAATTGTGAGTGGTAGTTAAGAAGTGTGGACCAACCAGT,1,.,.,.,.,.,.,45:G>A,snp,68.75,1,.,0,0,0,0,0,0,0,0,1,0,0,0 diff --git a/tests/test_docs.py b/tests/test_docs.py index 8fd5296..7b1009b 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -1,6 +1,6 @@ """Keep the command reference pages in step with the command-line parser. -Every option a subcommand accepts must appear in a table on its page in +Every option a published subcommand accepts must appear in a table on its page in docs/src/commands/, and every option those tables list must exist. Where a table gives a choice set or a plain default, it must match the parser too. """ @@ -12,6 +12,7 @@ import madcats COMMANDS_DIR = Path(__file__).resolve().parents[1] / "docs" / "src" / "commands" +UNPUBLISHED_COMMANDS: set = set() OPTION = re.compile(r"`(--[a-z0-9-]+)") CHOICES = re.compile(r"\{([^}]*)\}") @@ -56,6 +57,8 @@ def documented_default_matches(action: argparse.Action, cell: str): class CommandReferenceTests(unittest.TestCase): def test_option_tables_match_parser(self): for name, subparser in subcommand_parsers().items(): + if name in UNPUBLISHED_COMMANDS: + continue with self.subTest(command=name): page = COMMANDS_DIR / f"{name}.md" self.assertTrue(page.is_file(), f"no reference page for {name}") diff --git a/tests/test_example.py b/tests/test_example.py index 9e2f171..1b2336a 100644 --- a/tests/test_example.py +++ b/tests/test_example.py @@ -10,6 +10,7 @@ import madcats EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "madcats-demo" +V013 = Path(__file__).resolve().parent / "fixtures" / "generate_v013" def read_csv(path: Path): @@ -53,6 +54,25 @@ def test_rows_are_exactly_the_simulated_haplotypes(self): simulated = {(row["MarkerName"], row["TagSequence"]) for row in self.truth} self.assertEqual(emitted, simulated) + def test_untrimmed_tables_match_frozen_v013_output(self): + # Compare the entire table with output from the released implementation, + # including categories, Variants and all sample counts, not just row IDs. + with tempfile.TemporaryDirectory() as directory: + for rescue in ("on", "off"): + for tiles in ("auto", "off"): + with self.subTest(gapped_rescue=rescue, tile_groups=tiles): + output = Path(directory) / "madc.csv" + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + madcats.main([ + "generate", "--fastq-dir", str(EXAMPLE / "fastq"), + "--reference-tags", str(self.tags), + "--sample-lookup", str(EXAMPLE / "sample_names.csv"), + "--jobs", "1", "--remove-primers", "off", + "--gapped-rescue", rescue, "--tile-groups", tiles, + "--output", str(output), + ]) + self.assertEqual(output.read_bytes(), (V013 / f"gapped_{rescue}.csv").read_bytes()) + def test_undesigned_insertion_is_annotated(self): insertion = next(row for row in self.truth if row["Haplotype"] == "Insertion") row = next(row for row in self.rows if row["AlleleSequence"] == insertion["TagSequence"]) diff --git a/tests/test_filter_paralogs.py b/tests/test_filter_paralogs.py new file mode 100644 index 0000000..0bb3bfc --- /dev/null +++ b/tests/test_filter_paralogs.py @@ -0,0 +1,1056 @@ +"""filter-paralogs (madcats_paralogs.py): genome labels, placement, MADC +rewriting, and the optional mappy aligner. + +Most tests use a fake aligner with preset hits, so they run without mappy. +GenomeAlignerTests and ReviewCaseTests build small synthetic genomes and use +the real aligner; they are skipped when mappy is not installed. +""" +import contextlib +import csv +import importlib.util +import io +import json +import random +import subprocess +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path +from unittest import mock + +import madcats as mp +import madcats_paralogs as fp + +HAS_MAPPY = importlib.util.find_spec("mappy") is not None +REPOSITORY = Path(__file__).resolve().parents[1] +SAMPLES = ["S1", "S2", "S3"] + + +def hit(contig, start, end, score=162, strand=1): + return fp.GenomeHit(contig, start, end, strand, score) + + +class FakeAligner: + """Stands in for GenomeAligner: genome-wide hits are given up front, and the + window realignment scans the window ungapped on both strands.""" + + def __init__(self, genome, hits): + self.genome = genome + self.contigs = frozenset(genome) + self._hits = hits + self.windows = [] # every window realigned against, in order + + def new_buffer(self): + return None + + def hits(self, sequence, buffer): + return list(self._hits.get(sequence, ())) + + def fetch(self, contig, start, end): + return self.genome[contig][start:end] + + def window(self, contig, start, end): + self.windows.append((contig, start, end)) + return FakeWindow(contig, start, self.fetch(contig, start, end)) + + +class FakeWindow: + def __init__(self, contig, start, sequence): + self.contig, self.start, self.sequence = contig, start, sequence + + def hits(self, sequence, buffer=None): + found = [] + for strand, query in ((1, sequence), (-1, mp.reverse_complement(sequence))): + for offset in range(len(self.sequence) - len(query) + 1): + mismatches = sum(a != b for a, b in zip(query, self.sequence[offset:])) + if mismatches <= 6: + score = 2 * (len(query) - mismatches) - 8 * mismatches + found.append(fp.GenomeHit(self.contig, self.start + offset, self.start + offset + len(query), strand, score)) + return found + + +def madc_row(clone, category, sequence, counts, vendor=False): + stats = ["0.9", "0.5", "0.5", "0.2", "0.2", "0.6", "0.37", "0.4"] if vendor else ["."] * 8 + return [f"{clone}|{category}", clone, sequence, sequence, "1"] + stats + ["10", "10", "."] + [str(c) for c in counts] + + +def write_madc(path, rows, vendor=False, preamble=()): + header = list(mp.MADC_METADATA_COLUMNS) + if not vendor: + header = [mp.ANNOTATION_COLUMNS.get(column, column) for column in header] + with path.open("w", newline="") as handle: + writer = csv.writer(handle, lineterminator="\n") + writer.writerows(preamble) + writer.writerow(header + SAMPLES) + writer.writerows(rows) + + +def read_rows(path): + with path.open(newline="") as handle: + return list(csv.reader(handle)) + + +def read_dicts(path): + with path.open(newline="") as handle: + return list(csv.DictReader(handle)) + + +def mutate(sequence, position, base): + return sequence[:position] + base + sequence[position + 1 :] + + +def changed(sequence, *positions): + for position in positions: + sequence = mutate(sequence, position, "A" if sequence[position] != "A" else "C") + return sequence + + +class HitScoreTests(unittest.TestCase): + def test_score_matches_minimap2_short_read_scoring(self): + # (CIGAR, NM, matching bases, block length) as mappy reports them. + self.assertEqual(fp.hit_score([[81, 0]], 0, 81, 81), 162) + self.assertEqual(fp.hit_score([[81, 0]], 1, 80, 81), 80 * 2 - 8) + # An ambiguous base is outside the block, inside NM, and costs 1. + self.assertEqual(fp.hit_score([[81, 0]], 1, 80, 80), 80 * 2 - 1) + # A 1-base insertion costs 12 + 2; the inserted base is not a mismatch. + self.assertEqual(fp.hit_score([[40, 0], [1, 1], [40, 0]], 1, 80, 81), 160 - 14) + # A long deletion takes the cheaper long-gap piece: min(12 + 2*20, 24 + 20) = 44. + self.assertEqual(fp.hit_score([[40, 0], [20, 2], [41, 0]], 20, 81, 101), 162 - 44) + + def test_summarize_keeps_distinct_sites_best_first(self): + placement = fp.distinct_sites([ + hit("chrB", 500, 581), hit("chrA", 100, 181), hit("chrA", 103, 184), hit("chrC", 0, 81, score=150), + ]) + self.assertEqual([site.contig for site in placement.equal_best], ["chrA", "chrB"]) + self.assertEqual([site.score for site in placement.sites], [162, 162, 150]) + self.assertEqual(fp.distinct_sites([]).sites, ()) + + def test_adjacent_tandem_copies_stay_distinct(self): + # 81-base tags on adjacent copies of an 80-base repeat share one base: two loci, not one. + ref = fp.distinct_sites([hit("chr1", 500, 581), hit("chr1", 580, 661)], max_sites=None) + self.assertEqual(len(ref.sites), 2) + marker = fp.place_marker("chr1_540", ref, {"chr1"}, 81) + self.assertEqual( + (marker.placed_by, marker.ref_tag_site_count, marker.sites), + ("ref_tag+clone_id", 2, ref.sites[:1]), + ) + variant = fp.distinct_sites([hit("chr1", 500, 581, score=152), hit("chr1", 580, 661, score=152)]) + self.assertEqual(fp.genome_label(variant, marker).label, "ambiguous") + + def test_a_position_within_two_tandem_copies_picks_neither(self): + # The CloneID position lies in both adjacent copies, so it cannot choose between them, and + # every equal-best site stays the marker's, the copy on another contig included. + ref = fp.distinct_sites([hit("chr1", 500, 581), hit("chr1", 580, 661), hit("chr2", 100, 181)], max_sites=None) + marker = fp.place_marker("chr1_581", ref, {"chr1", "chr2"}, 81) + self.assertEqual( + (marker.placed_by, marker.clone_id_check, marker.ref_tag_site_count, marker.sites), + ("ref_tag_multicopy", "agree", 3, ref.sites), + ) + + +class PlacementTests(unittest.TestCase): + contigs = {"Chr1", "Chr2", "scaffold_12"} + + def test_clone_position_parsing(self): + self.assertEqual(fp.clone_position("Chr1_000333995", self.contigs), (("Chr1", 333995), None)) + self.assertEqual(fp.clone_position("scaffold_12_000345", self.contigs), (("scaffold_12", 345), None)) + self.assertEqual(fp.clone_position("marker7", self.contigs), (None, "no_position")) + self.assertEqual(fp.clone_position("Chr9_100", self.contigs), (None, "contig_absent")) + + def test_unique_ref_tag_is_cross_checked_against_the_clone_id(self): + ref = fp.GenomePlacement((hit("Chr1", 1000, 1081),)) + placed = fp.place_marker("Chr1_1060", ref, self.contigs, 81) + self.assertEqual((placed.placed_by, placed.clone_id_check, placed.sites), ("ref_tag", "agree", ref.equal_best)) + + def test_disagreeing_clone_id_is_checked_in_its_own_window(self): + # The Ref tag's best genome-wide site is on Chr2 (the search missed the design site, or this assembly + # carries the Alt allele there and a Ref-like copy on Chr2); the CloneID names Chr1:1043. + ref = fp.GenomePlacement((hit("Chr2", 7000, 7081, score=96),)) + windows = [] + + def align_ref_tag(*window): + windows.append(window) + return [hit("Chr1", 900, 981), hit("Chr1", 1000, 1081, score=156)] + + placed = fp.place_marker("Chr1_1043", ref, self.contigs, 81, align_ref_tag=align_ref_tag) + self.assertEqual(windows, [("Chr1", 1043 - 1 - 81 - fp.SITE_FLANK, 1043 + 81 + fp.SITE_FLANK)]) + self.assertEqual( + (placed.placed_by, placed.ref_tag_site_count, placed.clone_id_check), + ("clone_id_site", 1, "disagree"), + ) + self.assertEqual(placed.sites, (hit("Chr1", 1000, 1081, score=156),)) # the alignment covering the position + # A multi-copy Ref tag none of whose sites covers the position is checked the same way. + copies = fp.GenomePlacement((hit("Chr2", 7000, 7081), hit("Chr2", 9000, 9081))) + tied = fp.place_marker("Chr1_1043", copies, self.contigs, 81, align_ref_tag=align_ref_tag) + self.assertEqual((tied.placed_by, tied.ref_tag_site_count, tied.sites[0].contig), ("clone_id_site", 2, "Chr1")) + # Where the Ref tag does not align over the CloneID position, the marker is unplaced, so it keeps its rows. + lost = fp.place_marker("Chr1_1043", ref, self.contigs, 81, align_ref_tag=lambda *window: [hit("Chr1", 900, 981)]) + self.assertEqual( + (lost.placed_by, lost.sites, lost.ref_tag_site_count, lost.clone_id_check), + ("unplaced", (), 1, "disagree"), + ) + + def test_multicopy_ref_tag_resolved_by_clone_id_or_left_unresolved(self): + ref = fp.GenomePlacement((hit("Chr1", 1000, 1081), hit("Chr2", 5000, 5081))) + resolved = fp.place_marker("Chr2_5040", ref, self.contigs, 81) + self.assertEqual((resolved.placed_by, resolved.ref_tag_site_count), ("ref_tag+clone_id", 2)) + self.assertEqual([site.contig for site in resolved.sites], ["Chr2"]) + unresolved = fp.place_marker("marker7", ref, self.contigs, 81) + self.assertEqual((unresolved.placed_by, len(unresolved.sites)), ("ref_tag_multicopy", 2)) + + def test_unaligned_ref_tag_falls_back_to_the_clone_id_window(self): + fallback = fp.place_marker("Chr1_2000", fp.GenomePlacement(()), self.contigs, 81) + self.assertEqual((fallback.placed_by, fallback.clone_id_check), ("clone_id", "fallback")) + self.assertEqual(fallback.sites[0][:3], ("Chr1", 2000 - 1 - 81, 2000 + 81)) + self.assertEqual(fp.place_marker("marker7", None, self.contigs, 81).placed_by, "unplaced") + + def test_clone_positions_can_be_ignored(self): + def place(clone, *hits): + return fp.place_marker(clone, fp.GenomePlacement(hits), self.contigs, 81, use_clone_position=False) + + unique = place("Chr2_1060", hit("Chr1", 1000, 1081)) + self.assertEqual((unique.placed_by, unique.clone_id_check), ("ref_tag", "ignored")) + tied = place("Chr2_5040", hit("Chr1", 1000, 1081), hit("Chr2", 5000, 5081)) + self.assertEqual((tied.placed_by, len(tied.sites)), ("ref_tag_multicopy", 2)) # no CloneID tie-break + unaligned = place("Chr1_2000") + self.assertEqual((unaligned.placed_by, unaligned.sites, unaligned.clone_id_check), ("unplaced", (), "ignored")) + + def test_labels(self): + marker = fp.place_marker("Chr1_1060", fp.GenomePlacement((hit("Chr1", 1000, 1081),)), self.contigs, 81) + + def label(*hits, site_score=None): + return fp.genome_label(fp.distinct_sites(hits), marker, site_score).label + + self.assertEqual(label(hit("Chr1", 1000, 1081)), "on_target") + self.assertEqual(label(hit("Chr1", 1004, 1081, score=150)), "on_target") # clipped, same locus + self.assertEqual(label(hit("Chr2", 7000, 7081), hit("Chr1", 1000, 1081, score=150)), "paralog") + self.assertEqual(label(hit("Chr1", 1081, 1162)), "paralog") # the adjacent tandem copy + self.assertEqual(label(hit("Chr2", 7000, 7081), hit("Chr1", 1000, 1081)), "ambiguous") + self.assertEqual(label(hit("Chr2", 7000, 7081), hit("Chr2", 9000, 9081)), "paralog") # all ties elsewhere + self.assertEqual(label(), "unmapped") + # A diverged allele the genome-wide search missed, scored by the site realignment. + self.assertEqual(label(hit("Chr2", 7000, 7081, score=112), site_score=132), "on_target") + self.assertEqual(label(hit("Chr2", 7000, 7081, score=132), site_score=112), "paralog") + result = fp.genome_label(fp.distinct_sites([hit("Chr2", 7000, 7081, score=112)]), marker, 132) + self.assertEqual((result.target_score, result.target_from, result.off_target_score), (132, "site", 112)) + unplaced = fp.place_marker("marker7", None, self.contigs, 81) + self.assertEqual(fp.genome_label(fp.distinct_sites([hit("Chr1", 0, 81)]), unplaced).label, "unplaced") + multicopy = fp.place_marker( + "marker7", fp.GenomePlacement((hit("Chr1", 1000, 1081), hit("Chr2", 5000, 5081))), self.contigs, 81 + ) + self.assertEqual(fp.genome_label(fp.distinct_sites([hit("Chr1", 1000, 1081)]), multicopy).label, "ambiguous") + + def test_target_score_is_the_better_of_both_searches(self): + marker = fp.MarkerPlacement((hit("Chr1", 1000, 1081),), "ref_tag", 1, "agree") + off = hit("Chr2", 7000, 7081, score=122) + weaker = fp.genome_label(fp.distinct_sites([hit("Chr1", 1010, 1081, score=112), off]), marker, 132) + absent = fp.genome_label(fp.distinct_sites([off]), marker, 132) + self.assertEqual(weaker, absent) # a weaker genome-wide hit at the site changes nothing + self.assertEqual((weaker.label, weaker.target_score, weaker.target_from), ("on_target", 132, "site")) + stronger = fp.genome_label(fp.distinct_sites([hit("Chr1", 1000, 1081, score=142), off]), marker, 132) + self.assertEqual((stronger.label, stronger.target_score, stronger.target_from), ("on_target", 142, "genome")) + tied = fp.genome_label(fp.distinct_sites([hit("Chr1", 1000, 1081, score=132), off]), marker, 132) + self.assertEqual((tied.target_score, tied.target_from), (132, "genome")) + + +class FilterTests(unittest.TestCase): + """filter_paralogs on synthetic MADCs with preset genome-wide hits. + + One marker, tag at Chr1:1001-1081. The genome-wide search finds the + paralog's exact copy on Chr2 and an equal-scoring copy of the ambiguous + haplotype; it misses the diverged allele at its own site, which the + realignment to the marker's site then scores. + """ + + clone = "Chr1_001040" + + def setUp(self): + rng = random.Random(7) + + def other(base): + return "A" if base != "A" else "C" + + ref = "".join(rng.choice("ACGT") for _ in range(81)) + self.ref = ref + self.alt = mutate(ref, 40, other(ref[40])) + self.paralog = mutate(ref, 10, other(ref[10])) + self.ambiguous = mutate(ref, 60, other(ref[60])) + self.true_match = mutate(ref, 70, other(ref[70])) + self.diverged = mutate(mutate(mutate(ref, 5, other(ref[5])), 30, other(ref[30])), 75, other(ref[75])) + filler = "".join(rng.choice("ACGT") for _ in range(12000)) + genome = {"Chr1": filler[:1000] + ref + filler[1000:2000], "Chr2": filler[2000:12000]} + target = hit("Chr1", 1000, 1081) + self.aligner = FakeAligner(genome, { + self.ref: [target], + self.alt: [hit("Chr1", 1000, 1081, score=152)], + self.paralog: [hit("Chr2", 7000, 7081), hit("Chr1", 1000, 1081, score=152)], + self.ambiguous: [hit("Chr2", 9000, 9081, score=152), hit("Chr1", 1000, 1081, score=152)], + self.true_match: [hit("Chr1", 1000, 1081, score=152)], + self.diverged: [hit("Chr2", 5000, 5081, score=112)], + }) + self.specs = [ + ("Ref", self.ref, [10, 0, 5]), + ("Alt", self.alt, [0, 9, 5]), + ("RefMatch", self.paralog, [4, 4, 4]), + ("RefMatch", self.ambiguous, [1, 2, 0]), + ("AltMatch", self.true_match, [0, 3, 0]), + ("Other", self.diverged, [1, 1, 1]), + ] + self.rows = [madc_row(self.clone, *spec) for spec in self.specs] + self.temporary = tempfile.TemporaryDirectory() + self.dir = Path(self.temporary.name) + + def tearDown(self): + self.temporary.cleanup() + + def run_filter(self, madc, **options): + output = self.dir / "out_MADC.csv" + with contextlib.redirect_stderr(io.StringIO()): + summary = fp.filter_paralogs( + madc, output, self.aligner, self.dir / "labels.csv", self.dir / "markers.csv", **options + ) + return output, summary + + def test_default_drops_paralog_and_ambiguous_rows_and_tallies_reads(self): + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + output, summary = self.run_filter(madc) + kept = read_rows(output) + self.assertEqual(kept[0], read_rows(madc)[0]) # header untouched in drop mode + self.assertEqual(kept[1:], [self.rows[0], self.rows[1], self.rows[4], self.rows[5]]) # copied unchanged + rows = summary["rows"] + self.assertEqual(rows["input"], {"rows": 6, "reads": 50}) + self.assertEqual(rows["output"], {"rows": 4, "reads": 35}) + self.assertEqual(rows["by_label"]["paralog"], {"rows": 1, "reads": 12}) + self.assertEqual(rows["by_label"]["ambiguous"], {"rows": 1, "reads": 3}) + self.assertEqual(rows["by_outcome"]["dropped"], {"rows": 2, "reads": 15}) + self.assertEqual(rows["by_category"]["RefMatch"]["paralog"]["rows"], 1) + self.assertEqual( + summary["haplotypes"]["realigned_at_site"], {"haplotypes": 6, "found_at_site": 6, "target_from_site": 1} + ) + self.assertEqual(self.aligner.windows.count(("Chr1", 980, 1101)), 1) # the marker's site, indexed once + labels = {row["AlleleSequence"]: row for row in read_dicts(self.dir / "labels.csv")} + self.assertEqual(len(labels), 6) # dropped rows keep a record + paralog = labels[self.paralog] + self.assertEqual((paralog["Label"], paralog["Action"]), ("paralog", "dropped")) + self.assertEqual((paralog["TargetScore"], paralog["OffTargetScore"]), ("152", "162")) + self.assertEqual(paralog["OffTargetHit"], "Chr2:7001-7081(+)") # 1-based + self.assertEqual(labels[self.ambiguous]["Label"], "ambiguous") + diverged = labels[self.diverged] + self.assertEqual( + (diverged["Label"], diverged["TargetFrom"], diverged["TargetScore"]), + ("on_target", "site", "132"), + ) + self.assertEqual((labels[self.ref]["TargetFrom"], labels[self.ref]["OffTargetScore"]), ("genome", ".")) + markers = read_dicts(self.dir / "markers.csv") + self.assertEqual(markers[0]["Placement"], "ref_tag") + self.assertEqual(markers[0]["CloneIDCheck"], "agree") + self.assertEqual(markers[0]["Sites"], "Chr1:1001-1081(+)") + + def test_weaker_genome_wide_hit_at_the_site_does_not_hide_the_realignment(self): + # The genome-wide search aligns the diverged allele only partly at its site (112), below its Chr2 + # hit (122); realigned at the site it scores 132, so it is kept. + self.aligner._hits[self.diverged] = [hit("Chr2", 5000, 5081, score=122), hit("Chr1", 1010, 1081, score=112)] + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + self.run_filter(madc) + diverged = {row["AlleleSequence"]: row for row in read_dicts(self.dir / "labels.csv")}[self.diverged] + self.assertEqual( + (diverged["Label"], diverged["TargetScore"], diverged["TargetFrom"], diverged["OffTargetScore"]), + ("on_target", "132", "site", "122"), + ) + + def test_ref_tag_site_missing_from_the_genome_wide_hits(self): + # The genome-wide search returns only a weaker Chr2 site for the Ref tag. Aligned in the window + # around its CloneID position, the tag finds Chr1:1001-1081, which becomes the marker's site. + self.aligner._hits[self.ref] = [hit("Chr2", 6000, 6081, score=96)] + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + output, summary = self.run_filter(madc) + marker = read_dicts(self.dir / "markers.csv")[0] + self.assertEqual( + (marker["Placement"], marker["RefTagSites"], marker["CloneIDCheck"], marker["Sites"]), + ("clone_id_site", "1", "disagree", "Chr1:1001-1081(+)"), + ) + self.assertEqual(summary["markers"]["clone_id_disagreements"], [self.clone]) + self.assertEqual(read_rows(output)[1:], [self.rows[0], self.rows[1], self.rows[4], self.rows[5]]) + # Ignored, the CloneID cannot move the marker: it stays on Chr2, and the real AltMatch allele is dropped. + output, _ = self.run_filter(madc, clone_positions="ignore") + marker = read_dicts(self.dir / "markers.csv")[0] + self.assertEqual((marker["Placement"], marker["Sites"]), ("ref_tag", "Chr2:6001-6081(+)")) + labels = {row["AlleleSequence"]: row["Label"] for row in read_dicts(self.dir / "labels.csv")} + self.assertEqual(labels[self.true_match], "paralog") + + def test_ninth_equal_best_ref_tag_site(self): + # Nine exact copies of the Ref tag, and the one the CloneID names sorts after the eight a haplotype keeps. + self.aligner._hits[self.ref] = [hit("Chr1", start, start + 81) for start in range(0, 800, 100)] + [ + hit("Chr1", 1000, 1081) + ] + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + output, _ = self.run_filter(madc) + marker = read_dicts(self.dir / "markers.csv")[0] + self.assertEqual( + (marker["Placement"], marker["RefTagSites"], marker["CloneIDCheck"], marker["Sites"]), + ("ref_tag+clone_id", "9", "agree", "Chr1:1001-1081(+)"), + ) + self.assertEqual(read_rows(output)[1:], [self.rows[0], self.rows[1], self.rows[4], self.rows[5]]) + + def test_canonical_rows_are_never_dropped(self): + # The genome-wide search places this marker's Alt tag elsewhere, better than at its site. + self.aligner._hits[self.alt] = [hit("Chr2", 3000, 3081)] + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + output, summary = self.run_filter(madc) + self.assertIn(self.alt, [row[2] for row in read_rows(output)]) + self.assertEqual(summary["rows"]["by_outcome"]["protected"], {"rows": 1, "reads": 14}) + self.assertEqual(summary["rows"]["by_category"]["Alt"], {"paralog": {"rows": 1, "reads": 14}}) + + def test_flag_mode_labels_every_row_in_the_picref_column(self): + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + output, summary = self.run_filter(madc, paralog_action="flag", ambiguous_action="keep") + rows = read_rows(output) + column = rows[0].index("GenomeLabel") + self.assertEqual(column, mp.MADC_METADATA_COLUMNS.index("PICRef")) + self.assertEqual(len(rows[0]), 16 + len(SAMPLES)) + self.assertEqual( + [row[column] for row in rows[1:]], + ["on_target", "on_target", "paralog", "ambiguous", "on_target", "on_target"], + ) + self.assertEqual(summary["rows"]["by_outcome"]["flagged"]["rows"], 1) + self.assertEqual(summary["rows"]["by_outcome"]["kept"]["rows"], 5) + self.assertEqual(summary["genome_label_column"], "GenomeLabel") + # Filtering an already-flagged table rewrites the column in place. + again = self.dir / "again.csv" + with contextlib.redirect_stderr(io.StringIO()): + fp.filter_paralogs(output, again, self.aligner, self.dir / "l2.csv", self.dir / "m2.csv", paralog_action="flag") + self.assertEqual(read_rows(again), rows[:4] + rows[5:]) # ambiguous now dropped, nothing else changed + + def test_vendor_madc_keeps_preamble_and_statistics(self): + preamble = [ + [""] * 16 + ["DLet22"] * 3, + ["*"] * 16 + ["1", "1", "2"], + ["*"] * 16 + ["3077912", "3077913", "3077914"], + ] + vendor_rows = [madc_row(self.clone, *spec, vendor=True) for spec in self.specs] + madc = self.dir / "vendor.csv" + write_madc(madc, vendor_rows, vendor=True, preamble=preamble) + output, summary = self.run_filter(madc) + rows = read_rows(output) + self.assertEqual(rows[:3], preamble) + self.assertEqual(rows[3][11:13], ["PICSnp", "AvgPIC"]) + self.assertEqual(rows[4:], [vendor_rows[0], vendor_rows[1], vendor_rows[4], vendor_rows[5]]) + self.assertEqual(summary["rows"]["output"]["reads"], 35) + + def test_provenance_is_appended_to_a_madcats_preamble_only(self): + preamble = [["* MADCATS v0.13.0 tag_length=81"] + ["*"] * 15 + ["proj"] * 3] + madc = self.dir / "in.csv" + write_madc(madc, self.rows, preamble=preamble) + output, _ = self.run_filter(madc, provenance="filter-paralogs paralogs=drop") + self.assertEqual(read_rows(output)[0][0], "* MADCATS v0.13.0 tag_length=81 | filter-paralogs paralogs=drop") + + def test_flag_mode_needs_the_picref_column(self): + madc = self.dir / "short.csv" + with madc.open("w", newline="") as handle: + writer = csv.writer(handle, lineterminator="\n") + writer.writerow(["AlleleID", "CloneID", "AlleleSequence"] + SAMPLES) + writer.writerow(["Chr1_001040|Ref", "Chr1_001040", self.ref, "1", "2", "3"]) + with self.assertRaises(mp.MadcError): + self.run_filter(madc, paralog_action="flag") + output, summary = self.run_filter(madc) # drop mode works on the short layout + self.assertEqual(summary["rows"]["output"], {"rows": 1, "reads": 6}) + + def test_rows_without_an_allele_id_are_passed_over(self): + madc = self.dir / "in.csv" + blank = list(self.rows[2]) + blank[0] = "" + write_madc(madc, [self.rows[0], blank, self.rows[1], ["note"]]) + output, summary = self.run_filter(madc) + self.assertEqual(read_rows(output)[1:], [self.rows[0], self.rows[1]]) + self.assertEqual(summary["rows"]["input"]["rows"], 2) + self.assertEqual(len(read_dicts(self.dir / "labels.csv")), 2) + + def test_ambiguous_rows_can_be_flagged_while_paralogs_are_dropped(self): + madc = self.dir / "in.csv" + write_madc(madc, self.rows) + output, summary = self.run_filter(madc, ambiguous_action="flag") + rows = read_rows(output) + column = rows[0].index(fp.GENOME_LABEL_COLUMN) + self.assertEqual( + [row[column] for row in rows[1:]], ["on_target", "on_target", "ambiguous", "on_target", "on_target"] + ) + self.assertEqual(summary["rows"]["by_outcome"]["flagged"]["rows"], 1) + self.assertEqual(summary["rows"]["by_outcome"]["dropped"]["rows"], 1) + + def test_warnings_for_disagreeing_positions_and_for_no_placed_marker(self): + madc = self.dir / "in.csv" + # The CloneID names a position 5,000 bases from where the Ref tag aligns. + rows = [madc_row("Chr2_005000", category, sequence, counts) for category, sequence, counts in self.specs[:2]] + write_madc(madc, rows) + with contextlib.redirect_stderr(io.StringIO()) as log: + summary = fp.filter_paralogs(madc, self.dir / "o.csv", self.aligner, self.dir / "l.csv", self.dir / "m.csv") + self.assertEqual(summary["markers"]["clone_id_check"], {"disagree": 1}) + self.assertIn("CloneID positions disagree with the Ref tag's best genome sites for 1 of 1 markers", log.getvalue()) + self.assertIn("no marker could be placed on the genome; every row was kept", log.getvalue()) + self.assertEqual(summary["rows"]["output"]["rows"], 2) + + def test_clone_position_from_another_assembly(self): + # The Ref tag does not align, and the CloneID names Chr2:500, where this genome has no copy of the + # locus (as when CloneIDs carry another assembly's coordinates). Used, that position becomes the + # marker's site and the real AltMatch allele, aligning only at Chr1:1001, is dropped as a paralog. + self.aligner._hits[self.ref] = [] + clone = "Chr2_000500" + rows = [madc_row(clone, *spec) for spec in self.specs] + madc = self.dir / "in.csv" + write_madc(madc, rows) + _, used = self.run_filter(madc) + self.assertEqual(read_dicts(self.dir / "markers.csv")[0]["Placement"], "clone_id") + labels = {row["AlleleSequence"]: row for row in read_dicts(self.dir / "labels.csv")} + self.assertEqual((labels[self.true_match]["Label"], labels[self.true_match]["Action"]), ("paralog", "dropped")) + output, ignored = self.run_filter(madc, clone_positions="ignore") + self.assertEqual(ignored["markers"]["placement"], {"unplaced": 1}) + self.assertEqual(ignored["markers"]["clone_id_check"], {"ignored": 1}) + self.assertEqual(read_rows(output)[1:], rows) # an unplaced marker keeps every row + self.assertEqual({row["Label"] for row in read_dicts(self.dir / "labels.csv")}, {"unplaced"}) + + def test_hapapp_fixed_allele_id_madc(self): + # HapApp writes a leading Code_version column, then AlleleID, CloneID, AlleleSequence and the + # samples, with fixed IDs such as |Ref_0001; counts of rows it merged come out as floats. + self.aligner._hits[self.alt] = [hit("Chr2", 3000, 3081)] # the Alt tag aligns better elsewhere + fixed = {"Ref": "Ref_0001", "Alt": "Alt_0002"} + rows = [ + ["v1", f"{self.clone}|{fixed.get(category, f'{category}_{serial:04d}')}", self.clone, sequence] + + [f"{count}.0" for count in counts] + for serial, (category, sequence, counts) in enumerate(self.specs, 1) + ] + madc = self.dir / "hapapp.csv" + with madc.open("w", newline="") as handle: + writer = csv.writer(handle, lineterminator="\n") + writer.writerow(["Code_version", "AlleleID", "CloneID", "AlleleSequence"] + SAMPLES) + writer.writerows(rows) + output, summary = self.run_filter(madc) + self.assertEqual(read_rows(output), [read_rows(madc)[0], rows[0], rows[1], rows[4], rows[5]]) + self.assertEqual(summary["rows"]["input"], {"rows": 6, "reads": 50}) + self.assertEqual(set(summary["rows"]["by_category"]), {"Ref", "Alt", "RefMatch", "AltMatch", "Other"}) + self.assertEqual(summary["rows"]["by_outcome"]["protected"], {"rows": 1, "reads": 14}) + with self.assertRaises(mp.MadcError): # no PICRef column to carry a flag + self.run_filter(madc, paralog_action="flag") + parsed = mp.read_madc(madc) # validate reads it too + self.assertEqual(parsed["samples"], SAMPLES) + self.assertEqual(parsed["records"][0]["counts"], [10, 0, 5]) + + +class CountOverflowTests(unittest.TestCase): + """Vendor MADCs that stored counts in a signed byte: 128-255 come out negative.""" + + def test_signature_is_reported(self): + check = mp.CountOverflowCheck() + check.add("m1", [3, 127, -128, -2]) + check.add("m2", [0, 5]) + self.assertEqual(check.summary(), { + "negative_cells": 2, "markers_with_negative_cells": 1, "minimum": -128, "maximum": 127, + "signed_8bit_signature": True, + }) + self.assertIn("signed 8-bit overflow", check.warning(Path("x.csv"))) + clean = mp.CountOverflowCheck() + clean.add("m1", [0, 127, 300]) + self.assertIsNone(clean.warning(Path("x.csv"))) + self.assertFalse(clean.summary()["signed_8bit_signature"]) + + def test_both_readers_warn(self): + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "vendor.csv" + write_madc(madc, [madc_row("Chr1_001040", "Ref", "ACGT" * 20 + "A", [127, -100, 4], vendor=True)], vendor=True) + with contextlib.redirect_stderr(io.StringIO()) as log: + parsed = mp.read_madc(madc) + self.assertIn("negative read counts", log.getvalue()) + self.assertEqual(parsed["count_overflow"]["negative_cells"], 1) + aligner = FakeAligner({"Chr1": "A" * 2000}, {}) + with contextlib.redirect_stderr(io.StringIO()) as log: + summary = fp.filter_paralogs( + madc, Path(temporary) / "out.csv", aligner, Path(temporary) / "l.csv", Path(temporary) / "m.csv" + ) + self.assertIn("signed 8-bit overflow", log.getvalue()) + self.assertTrue(summary["count_overflow"]["signed_8bit_signature"]) + + def test_a_failed_run_leaves_no_partial_files(self): + tag = "ACGT" * 20 + "A" + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "in.csv" + write_madc(madc, [ + madc_row("Chr1_001040", "Ref", tag, [1, 2, 3]), + madc_row("Chr1_001040", "Alt", mutate(tag, 40, "C"), [1, "n/a", 3]), + ]) + outputs = [Path(temporary) / name for name in ("out.csv", "labels.csv", "markers.csv")] + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(mp.MadcError): + fp.filter_paralogs(madc, outputs[0], FakeAligner({"Chr1": "A" * 2000}, {}), outputs[1], outputs[2]) + self.assertEqual([path.exists() for path in outputs], [False, False, False]) + + def test_per_row_read_total_is_not_a_sample(self): + # Processed MADCs carry a readCountSum column between the sequence and the samples. + tag = "ACGT" * 20 + "A" + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "processed.csv" + with madc.open("w", newline="") as handle: + writer = csv.writer(handle, lineterminator="\n") + writer.writerow(["AlleleID", "CloneID", "AlleleSequence", "readCountSum"] + SAMPLES) + writer.writerow(["Chr1_001040|Ref", "Chr1_001040", tag, "50", "10", "15", "25"]) + parsed = mp.read_madc(madc) + self.assertEqual(parsed["samples"], SAMPLES) + self.assertEqual(parsed["records"][0]["counts"], [10, 15, 25]) + aligner = FakeAligner({"Chr1": "A" * 2000}, {}) + with contextlib.redirect_stderr(io.StringIO()): + summary = fp.filter_paralogs( + madc, Path(temporary) / "out.csv", aligner, Path(temporary) / "l.csv", Path(temporary) / "m.csv" + ) + self.assertEqual(summary["rows"]["input"], {"rows": 1, "reads": 50}) + self.assertEqual(read_rows(Path(temporary) / "out.csv"), read_rows(madc)) + + +class CommandTests(unittest.TestCase): + def test_missing_mappy_names_the_extra(self): + with mock.patch.dict(sys.modules, {"mappy": None}): + with self.assertRaises(mp.MadcError) as caught: + fp.GenomeAligner.open(Path("genome.fa"), None, 1) + self.assertIn("madcats[genome]", str(caught.exception)) + + def test_needs_a_genome_or_an_index(self): + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "in.csv" + madc.write_text("AlleleID,CloneID,AlleleSequence\n") + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as caught: + mp.main(["filter-paralogs", "--madc", str(madc), "--output", str(Path(temporary) / "out.csv")]) + self.assertEqual(caught.exception.code, 2) + + def test_missing_madc_and_output_over_the_input_are_refused(self): + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "in.csv" + arguments = ["filter-paralogs", "--genome", str(Path(temporary) / "genome.fa")] + with self.assertRaises(mp.MadcError) as caught: + fp.run_filter_paralogs(mp.build_parser().parse_args( + arguments + ["--madc", str(madc), "--output", str(Path(temporary) / "out.csv")] + )) + self.assertIn("MADC not found", str(caught.exception)) + madc.write_text("AlleleID,CloneID,AlleleSequence\n") + with self.assertRaises(mp.MadcError) as caught: + fp.run_filter_paralogs(mp.build_parser().parse_args( + arguments + ["--madc", str(madc), "--output", str(madc)] + )) + self.assertIn("must be a new file", str(caught.exception)) + + def test_madc_is_checked_before_the_genome_is_opened(self): + # A MADC without a header row is refused although the genome file does not exist. + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "in.csv" + madc.write_text("not,a,madc\n1,2,3\n") + with self.assertRaises(mp.MadcError) as caught: + fp.run_filter_paralogs(mp.build_parser().parse_args([ + "filter-paralogs", "--madc", str(madc), "--genome", str(Path(temporary) / "absent.fa"), + "--output", str(Path(temporary) / "out.csv"), + ])) + self.assertIn("header row", str(caught.exception)) + + def test_script_run_shares_madc_error_with_the_filter_module(self): + # python3 madcats.py runs the file as __main__; an error raised in madcats_paralogs must still + # be reported as "error: ..." with exit code 2, not a traceback. + with tempfile.TemporaryDirectory() as temporary: + madc = Path(temporary) / "in.csv" + madc.write_text("AlleleID,CloneID,AlleleSequence\n") + result = subprocess.run( + [sys.executable, str(REPOSITORY / "madcats.py"), "filter-paralogs", "--madc", str(madc), + "--output", str(Path(temporary) / "out.csv")], + capture_output=True, text=True, + ) + self.assertEqual(result.returncode, 2, result.stderr) + self.assertIn("error: filter-paralogs needs --genome", result.stderr) + + def test_other_commands_do_not_import_mappy(self): + with mock.patch.dict(sys.modules, {"mappy": None}): + with contextlib.redirect_stdout(io.StringIO()): + args = mp.build_parser().parse_args(["filter-paralogs", "--madc", "x", "--output", "y"]) + self.assertEqual((args.paralogs, args.ambiguous, args.clone_positions), ("drop", "drop", "use")) + + +@unittest.skipUnless(HAS_MAPPY, "mappy not installed (pip install 'madcats[genome]')") +class GenomeAlignerTests(unittest.TestCase): + """The real command on a synthetic 3-contig genome. + + Marker A sits on chr1 and has a 2-mismatch paralogous copy on chr2. Marker B + sits on chr1 and has a copy on chr3 differing at two positions, so a + haplotype carrying one base of each copy ties. Marker C's tag is + duplicated exactly on chr1 and chr3; its CloneID names the chr1 copy. + """ + + @classmethod + def setUpClass(cls): + rng = random.Random(11) + contigs = {name: [rng.choice("ACGT") for _ in range(6000)] for name in ("chr1", "chr2", "chr3")} + + def segment(name, start): + return "".join(contigs[name][start : start + 81]) + + def other(base): + return "A" if base != "A" else "C" + + cls.a_ref = segment("chr1", 1000) + copy = mutate(mutate(cls.a_ref, 20, other(cls.a_ref[20])), 50, other(cls.a_ref[50])) + contigs["chr2"][3000:3081] = copy + cls.a_paralog = copy # a perfect hit on chr2, two mismatches at the target + cls.a_alt = mutate(cls.a_ref, 40, other(cls.a_ref[40])) + cls.a_match = mutate(cls.a_ref, 65, other(cls.a_ref[65])) # one mismatch, only at the target + + cls.b_ref = segment("chr1", 4000) + b_copy = mutate(mutate(cls.b_ref, 30, other(cls.b_ref[30])), 60, other(cls.b_ref[60])) + contigs["chr3"][2000:2081] = b_copy + cls.b_alt = mutate(cls.b_ref, 45, other(cls.b_ref[45])) + cls.b_tie = mutate(cls.b_ref, 30, other(cls.b_ref[30])) # one mismatch against each copy + + cls.c_ref = segment("chr1", 5500) + contigs["chr3"][4500:4581] = cls.c_ref + cls.c_alt = mutate(cls.c_ref, 40, other(cls.c_ref[40])) + + cls.temporary = tempfile.TemporaryDirectory() + cls.dir = Path(cls.temporary.name) + cls.genome = cls.dir / "genome.fa" + with cls.genome.open("w") as handle: + for name, bases in contigs.items(): + handle.write(f">{name}\n{''.join(bases)}\n") + rows = [ + madc_row("chr1_001041", "Ref", cls.a_ref, [10, 0, 5]), + madc_row("chr1_001041", "Alt", cls.a_alt, [0, 10, 5]), + madc_row("chr1_001041", "RefMatch", cls.a_paralog, [6, 6, 6]), + madc_row("chr1_001041", "RefMatch", cls.a_match, [2, 0, 0]), + madc_row("chr1_004046", "Ref", cls.b_ref, [8, 8, 8]), + madc_row("chr1_004046", "Alt", cls.b_alt, [0, 4, 0]), + madc_row("chr1_004046", "RefMatch", cls.b_tie, [3, 3, 3]), + madc_row("chr1_005541", "Ref", cls.c_ref, [9, 9, 9]), + madc_row("chr1_005541", "Alt", cls.c_alt, [1, 1, 1]), + ] + cls.madc = cls.dir / "in_MADC.csv" + write_madc(cls.madc, rows) + cls.index = cls.dir / "genome.mmi" + cls.output = cls.dir / "out_MADC.csv" + with contextlib.redirect_stderr(io.StringIO()): + fp.run_filter_paralogs(mp.build_parser().parse_args([ + "filter-paralogs", "--madc", str(cls.madc), "--genome", str(cls.genome), + "--genome-index", str(cls.index), "--output", str(cls.output), "--jobs", "2", + ])) + cls.qc = json.loads(cls.output.with_suffix(".csv.qc.json").read_text()) + cls.labels = {row["AlleleSequence"]: row for row in read_dicts(cls.output.with_suffix(".csv.genome_labels.csv"))} + cls.markers = {row["CloneID"]: row for row in read_dicts(cls.output.with_suffix(".csv.genome_markers.csv"))} + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + def test_labels_from_the_genome(self): + expected = { + self.a_ref: "on_target", self.a_alt: "on_target", self.a_paralog: "paralog", self.a_match: "on_target", + self.b_ref: "on_target", self.b_alt: "on_target", self.b_tie: "ambiguous", + self.c_ref: "ambiguous", self.c_alt: "ambiguous", + } + self.assertEqual({sequence: row["Label"] for sequence, row in self.labels.items()}, expected) + self.assertTrue(self.labels[self.a_paralog]["OffTargetHit"].startswith("chr2:3001-3081")) + self.assertEqual(self.labels[self.a_paralog]["OffTargetScore"], "162") + + def test_marker_placement(self): + self.assertEqual(self.markers["chr1_001041"]["Sites"], "chr1:1001-1081(+)") + self.assertEqual(self.markers["chr1_001041"]["CloneIDCheck"], "agree") + multicopy = self.markers["chr1_005541"] + self.assertEqual((multicopy["Placement"], multicopy["RefTagSites"]), ("ref_tag+clone_id", "2")) + self.assertEqual(self.qc["markers"]["multicopy_ref_tags"], ["chr1_005541"]) + + def test_output_and_qc(self): + kept = [row[2] for row in read_rows(self.output)[1:]] + self.assertNotIn(self.a_paralog, kept) + self.assertNotIn(self.b_tie, kept) + self.assertIn(self.c_ref, kept) # canonical, protected despite its multi-copy tag + self.assertEqual(self.qc["rows"]["by_outcome"]["protected"]["rows"], 2) + self.assertEqual(self.qc["rows"]["by_outcome"]["dropped"], {"rows": 2, "reads": 27}) + self.assertEqual(self.qc["aligner"]["k"], 21) + + def test_saved_index_is_reused(self): + self.assertTrue(self.index.is_file()) + output = self.dir / "from_index_MADC.csv" + with contextlib.redirect_stderr(io.StringIO()) as log: + fp.run_filter_paralogs(mp.build_parser().parse_args( + ["filter-paralogs", "--madc", str(self.madc), "--genome-index", str(self.index), "--output", str(output)] + )) + self.assertIn("Loading index", log.getvalue()) + self.assertEqual(read_rows(output), read_rows(self.output)) + + def test_clone_positions_ignored(self): + # Marker C's Ref tag has equal-best copies on chr1 and chr3; only its CloneID picked chr1. + output = self.dir / "ignored_MADC.csv" + with contextlib.redirect_stderr(io.StringIO()): + fp.run_filter_paralogs(mp.build_parser().parse_args([ + "filter-paralogs", "--madc", str(self.madc), "--genome-index", str(self.index), + "--output", str(output), "--clone-positions", "ignore", + ])) + markers = {row["CloneID"]: row for row in read_dicts(output.with_suffix(".csv.genome_markers.csv"))} + self.assertEqual( + (markers["chr1_005541"]["Placement"], markers["chr1_005541"]["Sites"].count(";")), + ("ref_tag_multicopy", 1), + ) + self.assertEqual({row["CloneIDCheck"] for row in markers.values()}, {"ignored"}) + labels = {row["AlleleSequence"]: row["Label"] for row in read_dicts(output.with_suffix(".csv.genome_labels.csv"))} + self.assertEqual(labels, {sequence: row["Label"] for sequence, row in self.labels.items()}) + qc = json.loads(output.with_suffix(".csv.qc.json").read_text()) + self.assertEqual(qc["parameters"]["clone_positions"], "ignore") + + +@unittest.skipUnless(HAS_MAPPY, "mappy not installed (pip install 'madcats[genome]')") +class PlantedCopyTests(unittest.TestCase): + """Markers on one contig of a random genome, each with a diverged copy of its tag on another. + + The copies differ from the Ref tag at 1, 2, 4 or 8 bases, or at 1 base + and a 2-base deletion; four markers of each kind. Every marker has its + Ref and Alt rows, an allele of its own with one more substitution, and + two rows that come from the copy: the copy's tag, and that tag with one + more substitution. + """ + + KINDS = (("1", 1, 0), ("2", 2, 0), ("4", 4, 0), ("8", 8, 0), ("1_and_deletion", 1, 2)) + + @classmethod + def setUpClass(cls): + rng = random.Random(23) + home = [rng.choice("ACGT") for _ in range(30000)] + elsewhere = [rng.choice("ACGT") for _ in range(30000)] + + def other(base): + return rng.choice([choice for choice in "ACGT" if choice != base]) + + def substituted(sequence, positions): + for position in positions: + sequence = mutate(sequence, position, other(sequence[position])) + return sequence + + rows, cls.truth = [], {} + position = 1000 + for kind, substitutions, deleted in cls.KINDS: + for _ in range(4): + clone = f"home_{position + 41:06d}" + region = "".join(home[position - 100 : position + 181]) # the tag and 100 bases either side + ref = region[100:181] + changed_at = sorted(rng.sample(range(25, 70), substitutions)) + copy_region = substituted(region, [100 + offset for offset in changed_at]) + if deleted: + cut = rng.choice([offset for offset in range(30, 60) if offset not in changed_at]) + copy_region = copy_region[: 100 + cut] + copy_region[100 + cut + deleted :] + elsewhere[position : position + len(copy_region)] = copy_region + copy_tag = copy_region[100:181] + own_allele = substituted(ref, [72]) + copy_variant = substituted(copy_tag, [74]) + for category, sequence, origin in ( + ("Ref", ref, "home"), ("Alt", substituted(ref, [40]), "home"), ("RefMatch_1", own_allele, "home"), + ("RefMatch_2", copy_tag, "copy"), ("RefMatch_3", copy_variant, "copy"), + ): + rows.append(madc_row(clone, category, sequence, [8, 4, 0])) + cls.truth[(clone, sequence)] = (kind, origin) + position += 1400 + cls.temporary = tempfile.TemporaryDirectory() + cls.dir = Path(cls.temporary.name) + cls.genome = cls.dir / "genome.fa" + cls.genome.write_text(f">home\n{''.join(home)}\n>elsewhere\n{''.join(elsewhere)}\n") + cls.madc = cls.dir / "in_MADC.csv" + write_madc(cls.madc, rows) + + @classmethod + def tearDownClass(cls): + cls.temporary.cleanup() + + def filtered(self, name, madc=None, *options): + output = self.dir / f"{name}.csv" + with contextlib.redirect_stderr(io.StringIO()): + fp.run_filter_paralogs(mp.build_parser().parse_args([ + "filter-paralogs", "--madc", str(madc or self.madc), "--genome", str(self.genome), + "--genome-index", str(self.dir / "genome.mmi"), "--output", str(output), *options, + ])) + return output + + def test_copy_rows_are_paralogs_and_home_rows_are_on_target(self): + output = self.filtered("default") + labels = read_dicts(output.with_suffix(".csv.genome_labels.csv")) + self.assertEqual(len(labels), 100) + for row in labels: + kind, origin = self.truth[(row["CloneID"], row["AlleleSequence"])] + with self.subTest(kind=kind, allele=row["AlleleID"]): + self.assertEqual(row["Label"], "paralog" if origin == "copy" else "on_target") + self.assertEqual(row["Action"], "dropped" if origin == "copy" else "kept") + self.assertEqual(len(read_rows(output)), 1 + 60) + markers = read_dicts(output.with_suffix(".csv.genome_markers.csv")) + self.assertEqual(Counter(row["Placement"] for row in markers), {"ref_tag": 20}) + + def test_output_does_not_depend_on_the_number_of_threads(self): + one = self.filtered("one_thread", None, "--jobs", "1") + three = self.filtered("three_threads", None, "--jobs", "3") + for suffix in (".csv", ".csv.genome_labels.csv", ".csv.genome_markers.csv"): + self.assertEqual(one.with_suffix(suffix).read_bytes(), three.with_suffix(suffix).read_bytes()) + + def test_gzipped_madc_and_named_qc_file(self): + import gzip + + zipped = self.dir / "in_MADC.csv.gz" + zipped.write_bytes(gzip.compress(self.madc.read_bytes())) + qc_path = self.dir / "named.qc.json" + output = self.filtered("from_gzip", zipped, "--qc-output", str(qc_path)) + plain = self.filtered("from_plain") + self.assertEqual(output.read_bytes(), plain.read_bytes()) + self.assertEqual(json.loads(qc_path.read_text())["rows"]["by_label"]["paralog"]["rows"], 40) + self.assertFalse(output.with_suffix(".csv.qc.json").exists()) + + +@unittest.skipUnless(HAS_MAPPY, "mappy not installed (pip install 'madcats[genome]')") +class ReviewCaseTests(unittest.TestCase): + """Counterexamples from an external review (docs/DEVELOPMENT.md, "Review fixes"), each on a tiny genome with the real aligner.""" + + def setUp(self): + self.rng = random.Random(34) + self.temporary = tempfile.TemporaryDirectory() + self.dir = Path(self.temporary.name) + + def tearDown(self): + self.temporary.cleanup() + + def dna(self, length): + return "".join(self.rng.choice("ACGT") for _ in range(length)) + + def aligner(self, contigs, name="genome"): + fasta = self.dir / f"{name}.fa" + fasta.write_text("".join(f">{contig}\n{sequence}\n" for contig, sequence in contigs.items())) + with contextlib.redirect_stderr(io.StringIO()): + return fp.GenomeAligner.open(fasta, None, 1) + + def run_filter(self, aligner, rows): + madc = self.dir / "in.csv" + write_madc(madc, rows) + with contextlib.redirect_stderr(io.StringIO()): + fp.filter_paralogs(madc, self.dir / "out.csv", aligner, self.dir / "labels.csv", self.dir / "markers.csv") + labels = {row["AlleleSequence"]: row for row in read_dicts(self.dir / "labels.csv")} + return labels, read_dicts(self.dir / "markers.csv") + + def test_assembly_carrying_the_alt_allele_at_the_target(self): + # chr1 is the design site but carries the Alt allele; a paralog on chr2 carries Ref. The Ref tag + # aligns better on chr2, yet the marker is placed where its CloneID says. + ref = self.dna(81) + alt = changed(ref, 40) + allele = changed(alt, 65) # one SNP from the target, two from the paralog + aligner = self.aligner({"chr1": self.dna(500) + alt + self.dna(500), "chr2": self.dna(500) + ref + self.dna(500)}) + specs = [("Ref", ref, [5, 5, 5]), ("Alt", alt, [5, 5, 5]), ("AltMatch", allele, [3, 3, 3])] + labels, markers = self.run_filter(aligner, [madc_row("chr1_000540", *spec) for spec in specs]) + self.assertEqual( + (markers[0]["Placement"], markers[0]["CloneIDCheck"], markers[0]["Sites"]), + ("clone_id_site", "disagree", "chr1:501-581(+)"), + ) + found = labels[allele] + self.assertEqual( + (found["Label"], found["Action"], found["TargetScore"], found["OffTargetScore"]), ("on_target", "kept", "152", "142") + ) + # A CloneID position where the Ref tag does not align leaves the marker unplaced, keeping every row. + labels, markers = self.run_filter(aligner, [madc_row("chr1_000900", *spec) for spec in specs]) + self.assertEqual((markers[0]["Placement"], markers[0]["CloneIDCheck"]), ("unplaced", "disagree")) + self.assertEqual({(row["Label"], row["Action"]) for row in labels.values()}, {("unplaced", "kept")}) + + def test_markers_sharing_a_site_do_not_crowd_each_other_out(self): + # The allele has no 21-base seed at its own site, and its genome-wide hit is a 50-base partial copy. + ref = self.dna(81) + allele = changed(ref, 10, 30, 50, 70) + aligner = self.aligner({"target": self.dna(500) + ref + self.dna(500), "off": self.dna(500) + allele[:50] + self.dna(500)}) + for copies in (1, 30): # more markers on one site than the short-read preset returns hits + rows = [ + row for number in range(copies) + for row in (madc_row(f"m{number}", "Ref", ref, [9, 9, 9]), madc_row(f"m{number}", "RefMatch", allele, [3, 3, 3])) + ] + write_madc(self.dir / "in.csv", rows) + with contextlib.redirect_stderr(io.StringIO()): + fp.filter_paralogs( + self.dir / "in.csv", self.dir / "out.csv", aligner, self.dir / "labels.csv", self.dir / "markers.csv" + ) + found = Counter( + (row["Label"], row["TargetScore"], row["OffTargetScore"]) + for row in read_dicts(self.dir / "labels.csv") if row["AlleleID"].endswith("|RefMatch") + ) + self.assertEqual(found, {("on_target", "122", "100"): copies}) + + def test_adjacent_tandem_copies(self): + repeat = self.dna(80) + ref = repeat + repeat[0] + allele = changed(ref, 40) # one SNP from both copies + aligner = self.aligner({"chr1": self.dna(500) + repeat + repeat + repeat[0] + self.dna(500)}) + labels, markers = self.run_filter( + aligner, [madc_row("chr1_000540", "Ref", ref, [5, 5, 5]), madc_row("chr1_000540", "RefMatch", allele, [3, 3, 3])] + ) + self.assertEqual( + (markers[0]["Placement"], markers[0]["RefTagSites"], markers[0]["Sites"]), ("ref_tag+clone_id", "2", "chr1:501-581(+)") + ) + found = labels[allele] + self.assertEqual( + (found["Label"], found["TargetScore"], found["OffTargetScore"], found["OffTargetHit"]), + ("ambiguous", "152", "152", "chr1:581-661(+)"), + ) + + def test_multipart_index_is_refused(self): + import mappy + + parts = [] + for number in (1, 2): + fasta = self.dir / f"part{number}.fa" + fasta.write_text(f">chr{number}\n{self.dna(1000)}\n") + parts.append(self.dir / f"part{number}.mmi") + mappy.Aligner(str(fasta), preset="sr", fn_idx_out=str(parts[-1])) + joined = self.dir / "joined.mmi" # what minimap2 -I writes for a genome larger than its batch + joined.write_bytes(parts[0].read_bytes() + parts[1].read_bytes()) + self.assertEqual(fp._index_part_contigs(parts[0]), [["chr1"]]) + self.assertEqual(fp._index_part_contigs(joined), [["chr1"], ["chr2"]]) + self.assertIsNone(fp._index_part_contigs(self.dir / "part1.fa")) + truncated = self.dir / "truncated.mmi" + truncated.write_bytes(parts[0].read_bytes()[:-5]) + with self.assertRaises(mp.MadcError): + fp._index_part_contigs(truncated) + madc = self.dir / "in.csv" + write_madc(madc, [madc_row("chr1_000100", "Ref", self.dna(81), [1, 1, 1])]) + output = self.dir / "out.csv" + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(mp.MadcError) as caught: + fp.run_filter_paralogs(mp.build_parser().parse_args( + ["filter-paralogs", "--madc", str(madc), "--genome-index", str(joined), "--output", str(output)] + )) + self.assertIn("in 2 parts", str(caught.exception)) + self.assertFalse(output.exists()) + # The same file is refused when --genome names it. + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(mp.MadcError) as caught: + fp.run_filter_paralogs(mp.build_parser().parse_args( + ["filter-paralogs", "--madc", str(madc), "--genome", str(joined), "--output", str(output)] + )) + self.assertIn("in 2 parts", str(caught.exception)) + self.assertFalse(output.exists()) + # A one-part index given as --genome is loaded, and no copy is saved over --genome-index. + other = self.dir / "other.mmi" + with contextlib.redirect_stderr(io.StringIO()) as log: + fp.run_filter_paralogs(mp.build_parser().parse_args( + ["filter-paralogs", "--madc", str(madc), "--genome", str(parts[0]), "--genome-index", str(other), + "--output", str(output)] + )) + self.assertIn("Loading index", log.getvalue()) + self.assertFalse(other.exists()) + self.assertTrue(output.exists()) + + def test_label_change_between_assemblies_without_a_copy_change(self): + # Both assemblies have the target and one other copy; only the other copy's sequence differs. The + # label changes, so a label change alone does not show that a copy was gained or lost. + ref = self.dna(81) + allele = changed(ref, 40) + flanks = [self.dna(500) for _ in range(4)] + labels = [] + for name, copy in (("a", changed(ref, 20, 50)), ("b", allele)): + aligner = self.aligner({"target": flanks[0] + ref + flanks[1], "copy": flanks[2] + copy + flanks[3]}, name) + ref_placement = fp.distinct_sites(aligner.hits(ref, aligner.new_buffer()), max_sites=None) + marker = fp.place_marker("marker", ref_placement, aligner.contigs, 81, use_clone_position=False) + labels.append(fp.genome_label(fp.distinct_sites(aligner.hits(allele, aligner.new_buffer())), marker).label) + self.assertEqual(labels, ["on_target", "paralog"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_madcats.py b/tests/test_madcats.py index bc51093..28a0320 100644 --- a/tests/test_madcats.py +++ b/tests/test_madcats.py @@ -1,11 +1,15 @@ import argparse +import contextlib import csv +import dataclasses import gzip +import io import json import random import tempfile import unittest from pathlib import Path +from unittest import mock import madcats as mp @@ -284,8 +288,9 @@ def test_partial_defaults_resolve_from_tag_length(self): self.assertEqual(max(1, args.tag_length - mp.PARTIAL_TAIL_DEFAULT), 100) def test_one_reading_for_category_and_variants(self): - # A deletion inside the last 12 bases is not a verified reading: both the - # category (fixed offset) and the Variants (substitutions) ignore it. + # A deletion inside the last 12 bases is not a verified reading, yet it is + # cheaper than substitutions: the row is read up to it and no further. The + # target lies before it, so the category still reads it at the fixed offset. random.seed(11) ref = "".join(random.choice("ACGT") for _ in range(109)) alt = ref[:60] + ("A" if ref[60] != "A" else "C") + ref[61:] @@ -293,8 +298,9 @@ def test_one_reading_for_category_and_variants(self): tail_deletion = ref[:100] + ref[102:] + "GT" self.assertEqual(mp.classify_sequence(locus, tail_deletion, 20), "RefMatch") events = mp.variant_events(locus, tail_deletion, 20) - self.assertTrue(events and all(kind == "snp" for kind, *_ in events)) - self.assertEqual(mp.marker_type_label(locus, tail_deletion, 20, events), "snp") + self.assertEqual(events, [("unresolved", 101, ref[100:], tail_deletion[100:])]) + self.assertEqual(mp.format_variants(events), "unresolved=9") + self.assertEqual(mp.marker_type_label(locus, tail_deletion, 20, events), "unresolved") # A verified upstream deletion shifts the target for both consumers alike. shifted = ref[:30] + ref[31:60] + alt[60] + ref[61:] + "G" self.assertEqual(mp.classify_sequence(locus, shifted, 20), "AltMatch") @@ -1757,7 +1763,7 @@ def test_tail_gap_keeps_the_substitution_reading(self): # Deletion at 37 pushes ref[40]='C' into index 39 and appends a T. read = ref[:37] + ref[38:] + "T" self.assertEqual(read[variant_pos], "C") - self.assertEqual(mp.classify_sequence(locus, read), "Other") # fixed-offset reading, not the gapped one + self.assertEqual(mp.classify_sequence(locus, read), "Other") # neither reading: the target is not read def test_denoise_prefers_closer_parent_before_deeper(self): ref = "A" * 20 @@ -1858,6 +1864,137 @@ def test_fastq_records_leading_anchor_cuts_and_skips(self): self.assertEqual([seq for seq, _ in records], ["ACGTACGT", "TTTT"]) self.assertTrue(all(len(seq) == len(qual) for seq, qual in records)) + def test_locate_leading_anchor_with_one_substitution(self): + anchor = "GATGGATCCAGTGC" + tail = "ACGTTGCAAGCTTGACCGATAGGCTTACGG" + barcode = "TTCATAAGTTGC" + cut = len(barcode) + len(anchor) + # exact anchor: same cut either way, no mismatch spent + self.assertEqual(mp.locate_leading_anchor(barcode + anchor + tail, anchor, 1), (cut, 0)) + self.assertEqual(mp.locate_leading_anchor(barcode + anchor + tail, anchor, 0), (cut, 0)) + # one substitution, at either end or inside, and an N: recovered only with mismatches allowed + for position in (0, 6, len(anchor) - 1): + for base in ("A", "N"): + if anchor[position] == base: + continue + read = barcode + anchor[:position] + base + anchor[position + 1:] + tail + self.assertEqual(mp.locate_leading_anchor(read, anchor, 0), (-1, 0)) + self.assertEqual(mp.locate_leading_anchor(read, anchor, 1), (cut, 1)) + # two substitutions: no anchor + two = barcode + "C" + anchor[1:6] + "A" + anchor[7:] + tail + self.assertEqual(mp.locate_leading_anchor(two, anchor, 1), (-1, 0)) + # an exact copy wins over an earlier one-substitution placement + damaged = anchor[:3] + "C" + anchor[4:] + read = "AA" + damaged + "TTTT" + anchor + tail + self.assertEqual(mp.locate_leading_anchor(read, anchor, 1), (2 + len(anchor) + 4 + len(anchor), 0)) + # two one-substitution placements are ambiguous: no guessed cut + other = anchor[:9] + "T" + anchor[10:] + self.assertEqual(mp.locate_leading_anchor("AA" + damaged + "TT" + other + tail, anchor, 1), (-1, 0)) + # the placement must end inside the search window, as an exact anchor must + late = "C" * (mp.LEADING_ANCHOR_SEARCH + 1) + damaged + tail + self.assertEqual(mp.locate_leading_anchor(late, anchor, 1), (-1, 0)) + self.assertEqual(mp.locate_leading_anchor("C" * mp.LEADING_ANCHOR_SEARCH + damaged + tail, anchor, 1), + (mp.LEADING_ANCHOR_SEARCH + len(anchor), 1)) + # a read shorter than the anchor + self.assertEqual(mp.locate_leading_anchor(damaged[:-2], anchor, 1), (-1, 0)) + # an anchor shorter than the minimum is matched exactly, whatever is allowed + short = anchor[:9] + self.assertLess(len(short), mp.LEADING_ANCHOR_MISMATCH_MIN_LENGTH) + self.assertEqual(mp.locate_leading_anchor(barcode + short + tail, short, 1), (len(barcode) + len(short), 0)) + self.assertEqual(mp.locate_leading_anchor(barcode + "T" + short[1:] + tail, short, 1), (-1, 0)) + + def test_locate_leading_anchor_matches_a_full_scan(self): + # The pigeonhole search must find exactly the placements a scan of + # every window position finds. + anchor = "GATGGATCCAGTGC" + width = len(anchor) + + def scan(read): + end = min(width + mp.LEADING_ANCHOR_SEARCH, len(read)) + exact = read.find(anchor, 0, width + mp.LEADING_ANCHOR_SEARCH) + if exact >= 0: + return exact + width, 0 + hits = [start for start in range(0, end - width + 1) + if sum(a != b for a, b in zip(read[start:start + width], anchor)) <= 1] + return (hits[0] + width, 1) if len(hits) == 1 else (-1, 0) + + rng = random.Random(11) + for _ in range(3000): + prefix = "".join(rng.choice("ACGT") for _ in range(rng.randint(0, 45))) + body = list(anchor) + for _ in range(rng.choice([0, 1, 1, 2])): + body[rng.randrange(width)] = rng.choice("ACGTN") + read = prefix + "".join(body) + "".join(rng.choice("ACGT") for _ in range(rng.randint(0, 30))) + self.assertEqual(mp.locate_leading_anchor(read, anchor, 1), scan(read), read) + + def test_leading_anchor_mismatch_recovers_reads_and_is_keyed_only_when_used(self): + ref = "ACGTACGTACGTACGTACGT" + alt = ref[:6] + "T" + ref[7:] + locus = mp.Locus(0, "m1", ref[:6], "", "G", "T", 6, ref, alt) + anchor = "GATGGATCCAGTGC" + one = anchor[:-1] + "A" # the anchor's last base misread + two = "C" + anchor[1:-1] + "A" # two substitutions + with tempfile.TemporaryDirectory() as tmp: + fastq = Path(tmp) / "s1.fastq" + records = (["TTCATAAGTTGC" + anchor + ref + "CCGATC"] * 20 + + ["TTCATAAGTTGC" + one + ref + "CCGATC"] * 7 + + ["TTCATAAGTTGC" + two + ref + "CCGATC"] * 3 + + [ref + "CCGATCTGGG"] * 5) + with fastq.open("w") as handle: + for number, sequence in enumerate(records): + handle.write(f"@r{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + sample = mp.Sample("s1", "s1", str(fastq), {}) + base = dict(tag_length=20, max_offtarget_mismatches=4, primer_mismatches=1, + partial_min_length=30, gap_band=10, leading_anchor=anchor) + exact = mp.AssignmentSettings(**base, leading_anchor_mismatches=0) + tolerant = mp.AssignmentSettings(**base, leading_anchor_mismatches=1) + strict = mp.process_sample(sample, [locus], mp.PrimerIndex([locus]), exact) + loose = mp.process_sample(sample, [locus], mp.PrimerIndex([locus]), tolerant) + self.assertEqual(strict.counts[(0, ref)], 20) + self.assertEqual(strict.qc["reads_no_leading_anchor"], 15) + self.assertEqual(strict.qc.get("reads_leading_anchor_mismatch", 0), 0) + self.assertEqual(loose.counts[(0, ref)], 27) + self.assertEqual(loose.qc["reads_no_leading_anchor"], 8) + self.assertEqual(loose.qc["reads_leading_anchor_mismatch"], 7) + # The cache key changes only when the substitution can change the read + # pass, so exact-anchor and anchor-free caches stay valid. + self.assertNotIn("leading_anchor_mismatches", exact.cache_arguments()) + self.assertEqual(tolerant.cache_arguments()["leading_anchor_mismatches"], 1) + no_anchor = mp.AssignmentSettings(**{**base, "leading_anchor": ""}, leading_anchor_mismatches=1) + self.assertNotIn("leading_anchor_mismatches", no_anchor.cache_arguments()) + self.assertEqual(exact.cache_arguments(), mp.AssignmentSettings(**base).cache_arguments()) + # Parser defaults to exact leading-anchor matching (0 mismatches). + parsed = mp.build_parser().parse_args( + ["generate", "--fastq-dir", "f", "--reference-tags", "t", "--output", "o"] + ) + self.assertEqual(parsed.leading_anchor_mismatches, 0) + # An anchor too short for a substitution is matched exactly, so 1 keeps the key 0 gives. + short = {**base, "leading_anchor": anchor[:mp.LEADING_ANCHOR_MISMATCH_MIN_LENGTH - 1]} + self.assertEqual(mp.AssignmentSettings(**short, leading_anchor_mismatches=1).cache_arguments(), + mp.AssignmentSettings(**short, leading_anchor_mismatches=0).cache_arguments()) + + def test_infer_fuzzy_pass_cuts_raw_reads_at_the_anchor(self): + # The fuzzy pass once cleared the anchor it had just stored and voted + # with uncut raw reads; it must cut them as the exact pass does. + rng = random.Random(5) + flank = lambda n: "".join(rng.choice("ACGT") for _ in range(n)) + target = flank(40) + "[A/G]" + flank(40) + anchor = "GATGGATCCAGTGC" + with tempfile.TemporaryDirectory() as tmp: + design = Path(tmp) / "design.tsv" + design.write_text("MarkerName\tTargetSequence\n" + f"m1\t{target}\n") + windows = mp.enumerate_variant_windows(target, 30) + ref_window = sorted(windows.values())[0][0] + read_tag = ref_window[:25] + ("A" if ref_window[25] != "A" else "C") + ref_window[26:] # one error: fuzzy tier + fastq = Path(tmp) / "raw.fastq" + sequence = "TTCATAAGTTGC" + anchor + read_tag + "CCGATC" + fastq.write_text("".join(f"@r{n}\n{sequence}\n+\n{'I' * len(sequence)}\n" for n in range(5))) + mp._infer_fuzzy_init(str(design), 30, 3, ["m1"], (), anchor) + self.assertEqual(mp._INFER_STATE["leading_anchor"], anchor) + _, votes = mp._infer_fuzzy_scan(str(fastq)) + self.assertEqual(sum(votes.values()), 5) + self.assertTrue(all(marker == "m1" for marker, _key in votes)) + def test_raw_delivery_is_detected_and_named(self): anchor = "GATGGATCCAGTGC" tag = "ACGTACGTACGTACGTACGT" @@ -1897,6 +2034,125 @@ def test_raw_delivery_is_detected_and_named(self): # an explicit value is used as given, without reading the FASTQ self.assertEqual(mp.resolve_leading_anchor(argparse.Namespace(leading_anchor="acgt"), raw, prefixes, "generate"), "ACGT") + @staticmethod + def _write_raw_reads(path, reads): + with Path(path).open("w") as handle: + for number, sequence in enumerate(reads): + handle.write(f"@r{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + return Path(path) + + def test_leading_anchor_detection_with_barcodes_of_several_lengths(self): + # DArT inline barcodes have 10 to 14 bases, so the tag starts at five + # offsets and only a few files share the commonest one. Here the three + # files with 12-base barcodes all end in GT: read at the commonest + # offset alone, the anchor grows by those two bases and every sample + # whose barcode ends otherwise loses its reads. Each file gives its + # own prefix instead, and the anchor is what all eight share. + anchor = "CGATGGATCCAGTGC" + tag, other = "ACGTACGTACGTACGTACGT", "TTGCAAGCTTGACCGATAGG" + barcodes = ("TTCATAAGCAGT", "GGTAAGCATTGT", "ACCTGAGTACGT", "CAGGTCATGA", + "TGACCAGTTAG", "GATTACAGGCATA", "CCATAGGATTGACT", "AGTTCCGGAG") + # A candidate window that begins one base early (the last anchor base, + # then the tag) is found first in a quarter of the reads; the file's + # commonest prefix is still the whole one. + prefixes = {tag[:mp.LEADING_ANCHOR_PREFIX], other[:mp.LEADING_ANCHOR_PREFIX], anchor[-1] + other[:mp.LEADING_ANCHOR_PREFIX - 1]} + with tempfile.TemporaryDirectory() as tmp: + raws = [ + self._write_raw_reads( + Path(tmp) / f"raw_{number}.fastq", + [barcode + anchor + tag + "CCGATC"] * 150 + [barcode + anchor + other + "CCGATC"] * 50, + ) + for number, barcode in enumerate(barcodes) + ] + report = mp.detect_leading_anchor(raws, prefixes) + self.assertEqual(report["anchor"], anchor) + self.assertEqual(report["anchor_files"], len(barcodes)) + self.assertEqual(report["offsets"], (10 + len(anchor), 14 + len(anchor))) + self.assertEqual(report["shifted_rate"], 1.0) + with self.assertRaises(mp.MadcError) as context: + mp.resolve_leading_anchor(argparse.Namespace(leading_anchor=None), raws, prefixes, "generate") + message = str(context.exception) + self.assertIn(f"--leading-anchor {anchor} (or", message) + self.assertIn("tag start at offset 25 to 29", message) + self.assertNotIn("these files only", message) + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + self.assertEqual(mp.resolve_leading_anchor(argparse.Namespace(leading_anchor="auto"), raws, prefixes, "generate"), anchor) + self.assertNotIn("warning", stderr.getvalue()) + + def test_leading_anchor_from_one_or_two_files_is_used_and_flagged(self): + # One file cannot separate its barcode from the common sequence, and + # two may share barcode bases. The anchor still cuts those files where + # the amplicon starts, so it is used, with a warning not to reuse it. + anchor = "CGATGGATCCAGTGC" + tag = "ACGTACGTACGTACGTACGT" + prefixes = {tag[:mp.LEADING_ANCHOR_PREFIX]} + barcodes = ("TTCATAAGTTGA", "GGTAAGCATGCA", "ACCTGAGTACGT") # the first two end in the same base + with tempfile.TemporaryDirectory() as tmp: + raws = [ + self._write_raw_reads(Path(tmp) / f"raw_{number}.fastq", [barcode + anchor + tag + "CCGATC"] * 200) + for number, barcode in enumerate(barcodes) + ] + for files, expected, count in ((raws[:1], barcodes[0] + anchor, "1 FASTQ,"), (raws[:2], "A" + anchor, "2 FASTQs,")): + report = mp.detect_leading_anchor(files, prefixes) + self.assertEqual(report["anchor"], expected) + self.assertEqual(report["anchor_files"], len(files)) + stderr = io.StringIO() + args = argparse.Namespace(leading_anchor="auto") + with contextlib.redirect_stderr(stderr): + self.assertEqual(mp.resolve_leading_anchor(args, files, prefixes, "generate"), expected) + self.assertIn(f"warning: the leading anchor was detected from {count}", stderr.getvalue()) + # the anchor keeps every read of the files it came from + for fastq in files: + self.assertEqual(len(list(mp.fastq_records(fastq, expected))), 200) + with self.assertRaises(mp.MadcError) as context: + mp.resolve_leading_anchor(argparse.Namespace(leading_anchor=None), files, prefixes, "generate") + self.assertIn(f"--leading-anchor {expected} (or", str(context.exception)) + self.assertIn("these files only", str(context.exception)) + # three files are enough: no warning + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + self.assertEqual(mp.resolve_leading_anchor(argparse.Namespace(leading_anchor="auto"), raws, prefixes, "generate"), anchor) + self.assertNotIn("warning", stderr.getvalue()) + + def test_leading_anchor_detection_with_mixed_and_failed_files(self): + anchor = "CGATGGATCCAGTGC" + tag = "ACGTACGTACGTACGTACGT" + prefixes = {tag[:mp.LEADING_ANCHOR_PREFIX]} + barcodes = ("TTCATAAGTTGC", "GGTAAGCATGCA", "ACCTGAGTACGT", "CAGGTCATGATG", "TGACCAGTTAG") + with tempfile.TemporaryDirectory() as tmp: + # A file that mixes barcodes: its commonest prefix covers 40% of + # the reads, and an anchor that kept that barcode would drop the + # rest. The file gives what its barcodes share. + mixed = self._write_raw_reads( + Path(tmp) / "mixed.fastq", + [barcode + anchor + tag + "CCGATC" for barcode, copies in zip(barcodes, (80, 30, 30, 30, 30)) for _ in range(copies)], + ) + report = mp.detect_leading_anchor([mixed], prefixes) + self.assertEqual(report["anchor"], anchor) + self.assertEqual(len(list(mp.fastq_records(mixed, report["anchor"]))), 200) + # A failed sample, with a handful of reads that carry a tag after + # something else, does not hide the anchor of the others. + raws = [ + self._write_raw_reads(Path(tmp) / f"raw_{number}.fastq", [barcode + anchor + tag + "CCGATC"] * 200) + for number, barcode in enumerate(barcodes) + ] + failed = self._write_raw_reads( + Path(tmp) / "failed.fastq", ["TTTTTTTTTTTTTTTTTTTTTT" + tag + "CCGATC"] * 6 + ["GGGGGGGGGGGGGGGGGGGGGGGGGGGGGG"] * 194, + ) + report = mp.detect_leading_anchor(raws + [failed], prefixes) + self.assertEqual(report["anchor"], anchor) + self.assertEqual(report["anchor_files"], len(raws)) + # Files that end in two different sequences share no anchor, and auto says so. + others = [ + self._write_raw_reads(Path(tmp) / f"other_{number}.fastq", [barcode + "TTAGGCATCAAGCTA" + tag + "CCGATC"] * 200) + for number, barcode in enumerate(barcodes[:3]) + ] + self.assertEqual(mp.detect_leading_anchor(raws[:3] + others, prefixes)["anchor"], "") + with self.assertRaises(mp.MadcError) as context: + mp.resolve_leading_anchor(argparse.Namespace(leading_anchor="auto"), raws[:3] + others, prefixes, "generate") + self.assertIn("found no constant prefix", str(context.exception)) + def test_denoise_neighbour_lookup_matches_the_scan(self): # The distance-1 path enumerates neighbours instead of scanning # every centroid; it must pick exactly the parents the scan picks. @@ -1957,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") @@ -2214,3 +2470,198 @@ def test_variants_column_and_sidecar(self): self.assertEqual(set(cells.values()), {"."}) self.assertFalse(sidecar.exists()) self.assertIsNone(qc["output_summary"]["variants"]["sidecar"]) + + +class TileFamilyTests(unittest.TestCase): + """Tiles: two target SNPs inside one amplicon, read through one shared tag window.""" + + # SNPs at 10 (C/T) and 20 (G/A); both tiles start at the same primer. + AMPLICON = "ACGTACGGTA" + "C" + "TTGACCAGT" + "G" + "ATCCGTAGC" + + def tiles(self, groups=("", ""), iupac=True): + """Tile A (SNP at 10) and tile B (SNP at 20); with ``iupac`` each tag carries + the other tile's SNP as an ambiguity code, as DArTag panels write them.""" + amplicon = self.AMPLICON + ref_a = amplicon[:20] + ("R" if iupac else "G") + amplicon[21:] + ref_b = amplicon[:10] + ("Y" if iupac else "C") + amplicon[11:] + primer = amplicon[:8] + return [ + mp.Locus(0, "tileA", primer, "", "C", "T", 10, ref_a, ref_a[:10] + "T" + ref_a[11:], locus_group=groups[0]), + mp.Locus(1, "tileB", primer, "", "G", "A", 20, ref_b, ref_b[:20] + "A" + ref_b[21:], locus_group=groups[1]), + ] + + def test_tied_read_is_credited_to_every_tile(self): + loci = self.tiles() + self.assertEqual(mp.tile_families(loci), ((0, 1),)) + family_of = {0: (0, 1), 1: (0, 1)} + for read in (self.AMPLICON, self.AMPLICON[:10] + "T" + self.AMPLICON[11:]): + self.assertEqual(mp.select_markers(read, [0, 1], loci, 3, family_of=family_of), ((0, 1), "assigned")) + # Without the family the read ties and is dropped, as before. + self.assertEqual(mp.select_marker(read, [0, 1], loci, 3), (None, "ambiguous")) + + def test_untied_read_reaches_every_tile_it_fits(self): + # Tiles with identical tags and no ambiguity codes: a read carrying + # tile A's Alt fits A exactly and B with one substitution. It no longer + # goes to A alone; B sees it too, as it would in a panel of its own. + loci = self.tiles(iupac=False) + read = self.AMPLICON[:10] + "T" + self.AMPLICON[11:] + self.assertEqual(mp.select_marker(read, [0, 1], loci, 3), (0, "assigned")) + families = mp.tile_families(loci) + family_of = {member: family for family in families for member in family} + self.assertEqual(mp.select_markers(read, [0, 1], loci, 3, family_of=family_of), ((0, 1), "assigned")) + + def test_tile_group_modes(self): + self.assertEqual(mp.tile_families(self.tiles(), "declared"), ()) + self.assertEqual(mp.tile_families(self.tiles(), "off"), ()) + self.assertEqual(mp.tile_families(self.tiles(("amp1", "amp1")), "declared"), ((0, 1),)) + self.assertEqual(mp.tile_families(self.tiles(("amp1", "")), "auto"), ((0, 1),)) + # Markers declared in different groups are never linked. + self.assertEqual(mp.tile_families(self.tiles(("amp1", "amp2")), "auto"), ()) + # Different windows of one LocusGroup (normalize-reads tiling) are not one tag window. + window_a, window_b = self.tiles(("amp1", "amp1")) + shifted = mp.Locus(1, "tileB", self.AMPLICON[5:13], "", "G", "A", 15, self.AMPLICON[5:] + "AAAAA", + self.AMPLICON[5:20] + "A" + self.AMPLICON[21:] + "AAAAA", locus_group="amp1") + self.assertEqual(mp.tile_families([window_a, shifted]), ()) + + def test_tie_across_families_stays_ambiguous(self): + tile_a, tile_b = self.tiles(("amp1", "amp1")) + elsewhere = dataclasses.replace(tile_a, index=2, marker="elsewhere", locus_group="amp2") + loci = [tile_a, tile_b, elsewhere] + families = mp.tile_families(loci) + self.assertEqual(families, ((0, 1),)) + family_of = {member: family for family in families for member in family} + self.assertEqual(mp.select_markers(self.AMPLICON, [0, 1, 2], loci, 3, family_of=family_of), ((), "ambiguous")) + + def test_generate_counts_tiles_in_one_panel(self): + amplicon = self.AMPLICON + haplotypes = [amplicon] * 12 + [amplicon[:10] + "T" + amplicon[11:]] * 6 + [amplicon[:20] + "A" + amplicon[21:]] * 4 + partials = [amplicon[:26]] * 2 + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + fastq_dir = root / "fastq" + fastq_dir.mkdir() + with (fastq_dir / "s1.fastq").open("w") as handle: + for number, sequence in enumerate(haplotypes + partials): + handle.write(f"@r{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + tags = root / "tags.csv" + mp.write_reference_tags(tags, self.tiles()) # no LocusGroup: the tiles are detected + outcomes = {} + for mode in ("auto", "off"): + output = root / f"{mode}.csv" + self.assertEqual(mp.main(["generate", "--fastq-dir", str(fastq_dir), "--reference-tags", str(tags), + "--tag-length", "30", "--jobs", "1", "--reproducible-min-samples", "0", + "--depth-min-reads", "1", "--tile-groups", mode, + "--cache-dir", str(root / "cache"), "--output", str(output)]), 0) + totals = mp.Counter() + for record in mp.read_madc(output)["records"]: + totals[record["clone_id"]] += record["counts"][0] + with Path(str(output) + ".qc.json").open() as handle: + outcomes[mode] = (totals, json.load(handle)) + totals, qc = outcomes["auto"] + self.assertEqual(totals, {"tileA": 24, "tileB": 24}) + self.assertEqual(qc["tile_families"], [["tileA", "tileB"]]) + accounting = qc["read_accounting"] + self.assertEqual(accounting["reads_assigned_full_length"], 22) # each read once + self.assertEqual(accounting["tile_extra_credits_full_length"], 22) + self.assertEqual(accounting["tile_extra_credits_partial"], 2) + self.assertEqual( + accounting["reads_in_final_count_table"], + accounting["reads_assigned_full_length"] + accounting["tile_extra_credits_full_length"] + - accounting["reads_n_dropped"] + accounting["partial_reads_added_to_counts"], + ) + totals, qc = outcomes["off"] + self.assertEqual(totals, {"tileA": 0, "tileB": 0}) + self.assertEqual(qc["tile_families"], []) + 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]) diff --git a/tests/test_read_continuation.py b/tests/test_read_continuation.py new file mode 100644 index 0000000..ce5ca0d --- /dev/null +++ b/tests/test_read_continuation.py @@ -0,0 +1,480 @@ +"""Tests of read continuation. + +A row whose target lies in an unresolved end has two readings and too few +bases to choose. Reads longer than the tag show what follows it. ``generate`` +keeps the commonest of those bases, pools them over the samples, and decides +such a row again on the longer window. These tests pin that: the row settled +through its gap, the row settled as substitutions, the rows that stay +unresolved, the guard on the added bases, and a cohort whose reads end at the +tag, where nothing changes. +""" +import contextlib +import csv +import gzip +import io +import json +import sys +import tempfile +import unittest +from collections import Counter +from pathlib import Path +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO)) # the repository's modules, never an installed madcats +sys.path.insert(0, str(Path(__file__).resolve().parent)) # the helpers of test_unresolved + +import madcats as mp # noqa: E402 +from test_unresolved import BAND, LEFT, REF, locus_at, replay # noqa: E402 + +# The amplicon goes on after the 81-base tag. +AFTER = "CATTGACCTGAAGTCCATCGGTAAGCTTGA" +SEEN = 28 # bases of it a read shows + +# The target is the tag's last base, G; the Alt allele is C. +LOCUS = locus_at(80, alt_base="C") +# The tag of a Ref haplotype that lost base 79: its last three bases are those of REF moved up by +# one. It is also the tag of an Alt haplotype with two substitutions before the target. The tag +# cannot tell the two apart; the bases after it can. +LATE = REF[:78] + REF[79:] + AFTER[0] +LOST_A_BASE = AFTER[1 : SEEN + 1] # what follows the tag of the haplotype that lost a base +SUBSTITUTED = AFTER[:SEEN] # what follows the tag of the one with substitutions + + +# A Ref haplotype with three bases inserted after base 76. They push the last three Ref bases, +# the target among them, out of the tag. On the tag alone the cheapest alignment is another one: +# two substitutions and a deletion that the haplotype does not have. +INSERTION = (REF[:76] + "ACG" + REF[76:])[:81] +AFTER_INSERTION = (REF[78:] + AFTER)[:SEEN] + + +def continuations(after_row, after_ref=AFTER[:SEEN], after_alt=AFTER[:SEEN], locus=LOCUS, row=LATE): + """What row_decision is handed for one marker: {tag: the bases its reads carry after it}.""" + found = {locus.ref_tag: after_ref, locus.alt_tag: after_alt, row: after_row} + return {tag: bases for tag, bases in found.items() if bases} + + +def cell(locus, row, found): + return mp.format_variants(mp.variant_events(locus, row, BAND, found)) + + +def substituted(bases, count): + """``bases`` with ``count`` bases changed, spread out.""" + changed = list(bases) + for index in (5, 11, 17, 23)[:count]: + changed[index] = "A" if changed[index] != "A" else "C" + return "".join(changed) + + +class DecisionTests(unittest.TestCase): + def test_the_module_under_test_is_the_repository_s(self): + self.assertEqual(Path(mp.__file__).resolve().parent, REPO) + + def test_the_tag_alone_leaves_the_target_unread(self): + self.assertEqual(mp.row_decision(LOCUS, LATE, BAND), mp.RowDecision(None, (78, 78))) + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND), "Other") + self.assertEqual(cell(LOCUS, LATE, None), "unresolved=3") + + def test_a_row_settled_through_its_gap(self): + found = continuations(LOST_A_BASE) + reading, unresolved = mp.row_decision(LOCUS, LATE, BAND, found) + self.assertIsNone(unresolved) + self.assertEqual((reading.gap_bases, reading.end_read, reading.end_ref), (1, 80, 81)) + # Read through the deletion, the target shows the Ref base. + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND, found), "RefMatch") + events = mp.variant_events(LOCUS, LATE, BAND, found) + text = mp.format_variants(events) + self.assertEqual(text, "78:TG>T;overhang=1") + self.assertEqual(mp.marker_type_label(LOCUS, LATE, BAND, events), "indel") + self.assertEqual(replay(REF, text, LATE), LATE) + self.assertEqual(mp.parse_variants(text, REF, LATE), events) + + def test_a_row_settled_as_substitutions(self): + found = continuations(SUBSTITUTED) + self.assertEqual(mp.row_decision(LOCUS, LATE, BAND, found), mp.RowDecision(None, None)) + # Read at the fixed offsets, the target shows the Alt base. + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND, found), "AltMatch") + events = mp.variant_events(LOCUS, LATE, BAND, found) + self.assertEqual(mp.format_variants(events), "79:G>T;80:T>G;81:G>C") + self.assertEqual(mp.marker_type_label(LOCUS, LATE, BAND, events), "snp") + + def test_a_row_stays_unresolved_without_enough_bases_after_the_tag(self): + alone = mp.row_decision(LOCUS, LATE, BAND) + short = mp.GAP_VERIFIED_SUFFIX - 1 + cases = { + "no continuation of the row": continuations(""), + "no continuation of the Ref tag": continuations(LOST_A_BASE, after_ref=""), + "the row's is too short": continuations(LOST_A_BASE[:short]), + "the Ref tag's is too short": continuations(LOST_A_BASE, after_ref=AFTER[:short]), + "none at all": {}, + } + for name, found in cases.items(): + with self.subTest(name): + self.assertEqual(mp.row_decision(LOCUS, LATE, BAND, found), alone) + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND, found), "Other") + self.assertEqual(cell(LOCUS, LATE, found), "unresolved=3") + + def test_the_shortest_window_that_settles_adds_twelve_bases(self): + enough = mp.GAP_VERIFIED_SUFFIX + found = continuations(LOST_A_BASE[:enough], after_ref=AFTER[:enough], after_alt=AFTER[:enough]) + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND, found), "RefMatch") + + def test_the_alt_tag_borrows_the_ref_tag_s_continuation(self): + found = continuations(LOST_A_BASE, after_alt="") + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND, found), "RefMatch") + + def test_the_added_bases_must_be_read_cleanly(self): + # Two substitutions in the bases after the tag are sequence variation; three are a row + # that does not follow this amplicon, and the longer window then settles nothing. + allowed = mp.CONTINUATION_MAX_MISMATCHES + for after_row, settled in ((LOST_A_BASE, "RefMatch"), (SUBSTITUTED, "AltMatch")): + with self.subTest(settled): + found = continuations(substituted(after_row, allowed)) + self.assertEqual(mp.classify_sequence(LOCUS, LATE, BAND, found), settled) + found = continuations(substituted(after_row, allowed + 1)) + self.assertEqual(mp.row_decision(LOCUS, LATE, BAND, found), mp.row_decision(LOCUS, LATE, BAND)) + self.assertEqual(cell(LOCUS, LATE, found), "unresolved=3") + + def test_a_target_pushed_past_the_tag_stays_other(self): + # Three inserted bases push the last three Ref bases out of the tag. The longer window + # reads the insertion and finds the target after the tag. The row does not hold it. + row = (REF[:74] + "ACG" + REF[74:])[:81] + after_row = (REF[78:] + AFTER)[:SEEN] + pushed_out = locus_at(79) + found = continuations(after_row, locus=pushed_out, row=row) + self.assertEqual(mp.row_decision(pushed_out, row, BAND).unresolved, (75, 75)) + self.assertIsNone(mp.row_decision(pushed_out, row, BAND, found).unresolved) + self.assertEqual(mp.classify_sequence(pushed_out, row, BAND, found), "Other") + self.assertEqual(cell(pushed_out, row, found), "74:T>TACG;clip=3") + self.assertEqual(replay(REF, "74:T>TACG;clip=3", row), row) + # A target the insertion left in the tag is read from the same row. + kept_in = locus_at(76, alt_base="T") + found = continuations(after_row, locus=kept_in, row=row) + self.assertEqual(mp.classify_sequence(kept_in, row, BAND), "Other") + self.assertEqual(mp.classify_sequence(kept_in, row, BAND, found), "RefMatch") + + def test_a_settled_row_is_written_from_the_longer_window_s_alignment(self): + found = continuations(AFTER_INSERTION, row=INSERTION) + self.assertEqual(cell(LOCUS, INSERTION, None), "77:G>A;78:T>C;unresolved=2") + # The alignment the tag alone would be given, were its gap believed: + self.assertEqual(mp.format_variants(mp._describe(REF, INSERTION, BAND, True)), "77:G>A;78:T>C;79:GT>G;overhang=1") + # The longer window reads the insertion. The target is past the tag, so the row stays Other. + self.assertEqual(cell(LOCUS, INSERTION, found), "76:A>AACG;clip=3") + self.assertEqual(replay(REF, "76:A>AACG;clip=3", INSERTION), INSERTION) + self.assertEqual(mp.classify_sequence(LOCUS, INSERTION, BAND, found), "Other") + + def test_a_row_whose_target_the_tag_reads_is_never_asked(self): + before = locus_at(40) + found = continuations(LOST_A_BASE, locus=before) + self.assertEqual(mp.row_decision(before, LATE, BAND, found), mp.row_decision(before, LATE, BAND)) + self.assertEqual(mp.classify_sequence(before, LATE, BAND, found), "RefMatch") + self.assertEqual(cell(before, LATE, found), "unresolved=3") + + def test_canonical_rows_and_rescue_off_are_never_asked(self): + found = continuations(LOST_A_BASE) + for row in (LOCUS.ref_tag, LOCUS.alt_tag): + self.assertEqual(mp.row_decision(LOCUS, row, BAND, found), mp.RowDecision(None, None)) + self.assertEqual(mp.row_decision(LOCUS, LATE, 0, found), mp.RowDecision(None, None)) + + +class PoolingTests(unittest.TestCase): + def pooled(self, *samples): + results = [mp.SampleResult(mp.Sample("s", "s", "unused.fastq", {}), {}, {}, {}, {}, {}, continuations=kept) for kept in samples] + return mp.pooled_continuations(results) + + def test_samples_add_up_and_the_commonest_is_taken(self): + key = (0, LATE) + found, length = self.pooled({key: [(LOST_A_BASE, 2), (SUBSTITUTED, 1)]}, {key: [(LOST_A_BASE, 5)]}) + self.assertEqual((found, length), ({0: {LATE: LOST_A_BASE}}, SEEN)) + + def test_continuations_are_cut_to_the_length_most_reads_reach(self): + # Nine reads in ten show 16 bases, one shows 28: all are compared over 16. + key = (0, LATE) + found, length = self.pooled({key: [(LOST_A_BASE[:16], 9), (LOST_A_BASE, 1)]}) + self.assertEqual((found, length), ({0: {LATE: LOST_A_BASE[:16]}}, 16)) + # Reads that stop short of that length are left out. + found, length = self.pooled({key: [(LOST_A_BASE, 9), (SUBSTITUTED[:16], 1)]}) + self.assertEqual((found, length), ({0: {LATE: LOST_A_BASE}}, SEEN)) + + def test_a_tag_followed_by_two_sequences_has_no_continuation(self): + key = (0, LATE) + self.assertEqual(self.pooled({key: [(LOST_A_BASE, 5), (SUBSTITUTED, 5)]})[0], {}) + self.assertEqual(self.pooled({key: [(LOST_A_BASE, 6), (SUBSTITUTED, 4)]})[0], {0: {LATE: LOST_A_BASE}}) + + def test_a_continuation_needs_three_reads(self): + key = (0, LATE) + self.assertEqual(self.pooled({key: [(LOST_A_BASE, 2)]})[0], {}) + self.assertEqual(self.pooled({key: [(LOST_A_BASE, 3)]})[0], {0: {LATE: LOST_A_BASE}}) + + def test_no_continuation_anywhere(self): + self.assertEqual(self.pooled({}, {}), ({}, 0)) + + def test_shorter_read_marker_is_not_dropped_by_longer_read_markers(self): + # Marker 0 has 100 reads of 28-bp continuation; marker 1 has 5 reads of 16-bp continuation. + # Within marker 0, ref_tag has 100 reads of 28-bp while LATE has 5 reads of 16-bp. + found, length = self.pooled( + {(0, LOCUS.ref_tag): [(AFTER[:SEEN], 100)], (0, LATE): [(LOST_A_BASE[:16], 5)], (1, LATE): [(LOST_A_BASE[:16], 5)]} + ) + self.assertEqual(length, SEEN) + self.assertEqual(found, {0: {LOCUS.ref_tag: AFTER[:SEEN], LATE: LOST_A_BASE[:16]}, 1: {LATE: LOST_A_BASE[:16]}}) + + def test_share_uses_all_continuation_reads_not_only_top_three(self): + # 5 reads of one continuation + 5 distinct singleton continuations = 5/10 (50% < 60%), not 5/7. + counts = Counter({LOST_A_BASE: 5}) + for pos in (0, 1, 2, 3, 4): + alt_tail = list(SUBSTITUTED) + alt_tail[pos] = "A" if alt_tail[pos] != "A" else "C" + counts["".join(alt_tail)] = 1 + self.assertEqual(sum(counts.values()), 10) + kept, residuals = mp._compact_continuations(counts) + self.assertTrue(residuals) + result = mp.SampleResult( + mp.Sample("s", "s", "unused.fastq", {}), {}, {}, {}, {}, {}, + continuations={(0, LATE): kept}, continuation_residuals={(0, LATE): residuals}, + ) + found, _ = mp.pooled_continuations([result]) + self.assertEqual(found, {}) + + def test_length_variants_of_one_sequence_are_not_undercounted(self): + # One biological continuation arriving at ten different read lengths (18..27 bp) + # collapses into one family so none of its reads are dropped into residuals. + counts = Counter({LOST_A_BASE[:length]: 2 for length in range(18, 28)}) + kept, residuals = mp._compact_continuations(counts) + self.assertEqual(residuals, []) + found, _ = self.pooled({(0, LATE): kept}) + self.assertEqual(found, {0: {LATE: LOST_A_BASE[:19]}}) + + def test_noisy_tails_past_pooled_length_still_count_toward_shared_prefix(self): + # Mirrors pecan Chr11_11965289: 107 reads share the same first 28 bases with noisy G/T tails + # after base 28, alongside 66 unrelated reads (107/173 = 61.8% >= 60%). + base = LOST_A_BASE[:28] + counts = Counter({ + base + "G": 35, base: 28, base + "GGG": 26, base + "TGG": 7, + base + "T": 5, base + "GGT": 3, base + "GTG": 2, base + "TTG": 1, + }) + for pos in range(11): + other = list(SUBSTITUTED[:28]) + other[pos] = "A" if other[pos] != "A" else "C" + counts["".join(other)] = 6 + kept, residuals = mp._compact_continuations(counts) + with tempfile.TemporaryDirectory() as directory: + dummy = Path(directory) / "s.fastq" + dummy.write_text("") + cache = Path(directory) / "s.json.gz" + sample = mp.Sample("s", "s", str(dummy), {}) + original = mp.SampleResult( + sample, {(0, LATE): 173}, {}, {}, {}, {}, + continuations={(0, LATE): kept}, continuation_residuals={(0, LATE): residuals}, + ) + mp._write_cache(cache, original, dummy.stat()) + loaded = mp._load_cache(cache, sample, dummy.stat()) + self.assertIsNotNone(loaded) + self.assertEqual(loaded.continuation_residuals, original.continuation_residuals) + found, length = mp.pooled_continuations([loaded]) + self.assertEqual((found, length), ({0: {LATE: base}}, 28)) + + +class GenerateTests(unittest.TestCase): + """``generate`` from FASTQ files: one marker, two samples, reads of the Ref, Alt and LATE tags.""" + + PLAIN = REF[:50] + "A" + REF[51:] # a Ref haplotype with one substitution: the tag decides it + + def write_reads(self, directory, name, after_tag, after_late): + """Two samples' reads, each tag followed by ``after_tag`` bases; LATE by those of ``after_late``.""" + reads = Path(directory) / f"reads_{name}" + reads.mkdir() + rows = [(LOCUS.ref_tag, AFTER, 40), (LOCUS.alt_tag, AFTER, 30), (self.PLAIN, AFTER, 12), (LATE, after_late, 12)] + for sample in ("s1", "s2"): + with gzip.open(reads / f"{sample}.fastq.gz", "wt") as handle: + number = 0 + for tag, following, copies in rows: + sequence = tag + following[:after_tag] + for _ in range(copies): + number += 1 + handle.write(f"@{sample}_{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + return reads + + def generate(self, directory, reads, cache=None): + """Run generate on ``reads``: (table path, {sequence: row}, the QC file's output summary).""" + panel = Path(directory) / "tags.csv" + mp.write_reference_tags(panel, [LOCUS]) + output = Path(directory) / f"{reads.name}.csv" + arguments = [ + "generate", "--fastq-dir", str(reads), "--reference-tags", str(panel), "--tag-length", "81", + "--jobs", "1", "--output", str(output), + ] + if cache is not None: + arguments += ["--cache-dir", str(cache)] + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(mp.main(arguments), 0) + with open(output, newline="") as handle: + table = {row["AlleleSequence"]: row for row in csv.DictReader(handle)} + with open(str(output) + ".qc.json") as handle: + summary = json.load(handle)["output_summary"] + return output, table, summary + + def run_generate(self, directory, name, after_tag, after_late): + return self.generate(directory, self.write_reads(directory, name, after_tag, after_late)) + + def test_reads_that_end_at_the_tag_change_nothing(self): + # Reads that stop at the tag, or two bases after it, give the same table: the row's + # target stays unread and nothing is kept from after the tag. + with tempfile.TemporaryDirectory() as directory: + at_tag, table, summary = self.run_generate(directory, "at_tag", 0, LOST_A_BASE) + two_more, _, summary_two = self.run_generate(directory, "two_more", 2, LOST_A_BASE) + self.assertEqual(at_tag.read_bytes(), two_more.read_bytes()) + for found in (summary, summary_two): + self.assertEqual(found["read_continuation"], {"bases_after_tag": 0, "rows_settled": 0, "reads_settled": 0}) + self.assertEqual(found["unresolved_ends"]["rows_target_not_read"], 1) + self.assertEqual((table[LATE]["AlleleID"], table[LATE]["Variants"]), ("m1|Other", "unresolved=3")) + + def test_longer_reads_settle_the_row_and_only_that_row(self): + with tempfile.TemporaryDirectory() as directory: + _, before, _ = self.run_generate(directory, "at_tag", 0, LOST_A_BASE) + cache = Path(directory) / "cache" + reads = self.write_reads(directory, "longer", SEEN, LOST_A_BASE) + output, table, summary = self.generate(directory, reads, cache) + self.assertEqual( + (table[LATE]["AlleleID"], table[LATE]["Variants"], table[LATE]["MarkerType"]), + ("m1|RefMatch", "78:TG>T;overhang=1", "indel"), + ) + self.assertEqual(summary["read_continuation"], {"bases_after_tag": SEEN, "rows_settled": 1, "reads_settled": 24}) + self.assertEqual(summary["unresolved_ends"]["rows"], 0) + self.assertEqual(set(table), set(before)) + for sequence in set(table) - {LATE}: + self.assertEqual(table[sequence], before[sequence]) + self.assertEqual((table[LATE]["s1"], table[LATE]["s2"]), (before[LATE]["s1"], before[LATE]["s2"])) + # The read pass kept what follows the two canonical tags and the unread row from + # their first read on, and nothing of the row the tag decides. + with gzip.open(sorted(cache.glob("s1.*.json.gz"))[0], "rt") as handle: + kept = {tag: found for _, tag, _, *found in json.load(handle)["counts"]} + self.assertEqual( + kept, + {LOCUS.ref_tag: [[SUBSTITUTED, 40]], LOCUS.alt_tag: [[SUBSTITUTED, 30]], LATE: [[LOST_A_BASE, 12]], self.PLAIN: []}, + ) + # A second run takes them from the cache and writes the same table. + first = output.read_bytes() + with mock.patch.object(mp, "_write_cache", side_effect=AssertionError("the cache was not used")): + again, _, _ = self.generate(directory, reads, cache) + self.assertEqual(again.read_bytes(), first) + + def test_the_same_tag_settles_the_other_way_when_its_reads_say_so(self): + with tempfile.TemporaryDirectory() as directory: + _, table, _ = self.run_generate(directory, "substituted", SEEN, SUBSTITUTED) + self.assertEqual( + (table[LATE]["AlleleID"], table[LATE]["Variants"], table[LATE]["MarkerType"]), + ("m1|AltMatch", "79:G>T;80:T>G;81:G>C", "snp"), + ) + + def test_buffered_first_two_reads_make_category_invariant_to_fastq_order(self): + # 17 deletion continuations vs 13 substitution continuations (17/30 = 56.7% < 60%) must give + # Other regardless of FASTQ record order, while 3 reads per sample across 2 samples (6 total) + # flushes the 2-read buffer on read #3 and settles the row. + ambiguous_streams = ( + [(LATE, LOST_A_BASE)] * 17 + [(LATE, SUBSTITUTED)] * 13, + [(LATE, SUBSTITUTED)] * 13 + [(LATE, LOST_A_BASE)] * 17, + ) + with tempfile.TemporaryDirectory() as directory: + panel = Path(directory) / "tags.csv" + mp.write_reference_tags(panel, [LOCUS]) + for idx, stream in enumerate(ambiguous_streams): + reads = Path(directory) / f"order_{idx}" + reads.mkdir() + with gzip.open(reads / "s1.fastq.gz", "wt") as handle: + records = [(LOCUS.ref_tag, AFTER[:SEEN])] * 30 + stream + for num, (tag, tail) in enumerate(records, 1): + seq = tag + tail + handle.write(f"@r{num}\n{seq}\n+\n{'I' * len(seq)}\n") + out = Path(directory) / f"order_{idx}.csv" + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual( + mp.main([ + "generate", "--fastq-dir", str(reads), "--reference-tags", str(panel), + "--tag-length", "81", "--jobs", "1", "--reproducible-min-samples", "0", + "--depth-min-reads", "10", "--output", str(out), + ]), + 0, + ) + with open(out, newline="") as handle: + table = {row["AlleleSequence"]: row for row in csv.DictReader(handle)} + self.assertEqual(table[LATE]["AlleleID"], "m1|Other") + # And 3 reads per sample across 2 samples counts all 6 buffered continuations and settles. + reads3 = Path(directory) / "three_each" + reads3.mkdir() + for sample in ("s1", "s2"): + with gzip.open(reads3 / f"{sample}.fastq.gz", "wt") as handle: + num = 0 + for tag, tail, copies in ((LOCUS.ref_tag, AFTER[:SEEN], 20), (LOCUS.alt_tag, AFTER[:SEEN], 20), (LATE, LOST_A_BASE, 3)): + for _ in range(copies): + num += 1 + seq = tag + tail + handle.write(f"@{sample}_{num}\n{seq}\n+\n{'I' * len(seq)}\n") + out3 = Path(directory) / "three_each.csv" + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual( + mp.main([ + "generate", "--fastq-dir", str(reads3), "--reference-tags", str(panel), + "--tag-length", "81", "--jobs", "1", "--reproducible-min-reads", "3", + "--reproducible-min-samples", "2", "--output", str(out3), + ]), + 0, + ) + with open(out3, newline="") as handle: + table3 = {row["AlleleSequence"]: row for row in csv.DictReader(handle)} + self.assertEqual( + (table3[LATE]["AlleleID"], table3[LATE]["Variants"], table3[LATE]["MarkerType"]), + ("m1|RefMatch", "78:TG>T;overhang=1", "indel"), + ) + + def test_table_without_primers_carries_the_settled_reading(self): + # The rows without their primers are not aligned again: each settled row is written from + # the alignment it was settled with, in the positions of the Ref row as printed. + with tempfile.TemporaryDirectory() as directory: + results = [] + for sample in ("s1", "s2"): + counts = {(0, LOCUS.ref_tag): 40, (0, LOCUS.alt_tag): 30, (0, LATE): 12, (0, INSERTION): 12} + kept = { + (0, LOCUS.ref_tag): [(SUBSTITUTED, 40)], (0, LATE): [(LOST_A_BASE, 12)], (0, INSERTION): [(AFTER_INSERTION, 12)], + } + results.append(mp.SampleResult(mp.Sample(sample, sample, "unused.fastq", {}), counts, {}, {}, {}, {}, continuations=kept)) + output = Path(directory) / "madc.csv" + mp.write_madc( + output, [LOCUS], results, mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0), mp.OutputOptions(remove_primers=True), BAND, + ) + with open(output, newline="") as handle: + table = {row["AlleleSequence"]: row for row in csv.DictReader(handle)} + row = table[LATE[LEFT:]] + self.assertEqual((row["AlleleID"], row["Variants"], row["MarkerType"]), ("m1|RefMatch", "58:TG>T;overhang=1", "indel")) + self.assertEqual(replay(REF[LEFT:], row["Variants"], LATE[LEFT:]), LATE[LEFT:]) + row = table[INSERTION[LEFT:]] + self.assertEqual((row["AlleleID"], row["Variants"], row["MarkerType"]), ("m1|Other", "56:A>AACG;clip=3", "indel")) + self.assertEqual(replay(REF[LEFT:], row["Variants"], INSERTION[LEFT:]), INSERTION[LEFT:]) + + def test_a_settled_row_with_a_gap_in_its_left_primer_is_described_from_the_bases_shown(self): + # Two bases inserted in the left primer shift the row against the Ref row from there on, so + # the two rows as printed start at different bases of the alignment. It is not carried + # then: the printed rows are aligned as they stand, and the cell still rebuilds the row. + whole = REF[:8] + "GG" + REF[8:75] + "ACG" + REF[75:] + AFTER + row, after_row = whole[:81], whole[81 : 81 + SEEN] + found = continuations(after_row, row=row) + self.assertEqual(cell(LOCUS, row, None), "8:A>AGG;unresolved=5") # early verified gap is kept; only the late end is unresolved + self.assertEqual(cell(LOCUS, row, found), "8:A>AGG;75:A>AACG;clip=5") + with tempfile.TemporaryDirectory() as directory: + results = [] + for sample in ("s1", "s2"): + counts = {(0, LOCUS.ref_tag): 40, (0, LOCUS.alt_tag): 30, (0, row): 12} + kept = {(0, LOCUS.ref_tag): [(SUBSTITUTED, 40)], (0, row): [(after_row, 12)]} + results.append(mp.SampleResult(mp.Sample(sample, sample, "unused.fastq", {}), counts, {}, {}, {}, {}, continuations=kept)) + output = Path(directory) / "madc.csv" + mp.write_madc( + output, [LOCUS], results, mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0), mp.OutputOptions(remove_primers=True), BAND, + ) + with open(output, newline="") as handle: + table = {entry["AlleleSequence"]: entry for entry in csv.DictReader(handle)} + shown = table[row[LEFT:]] + self.assertEqual((shown["AlleleID"], shown["Variants"]), ("m1|Other", "1:.>AC;56:A>AC;58:T>A;clip=3")) + self.assertEqual(replay(REF[LEFT:], shown["Variants"], row[LEFT:]), row[LEFT:]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_reading_ties.py b/tests/test_reading_ties.py new file mode 100644 index 0000000..1373e0e --- /dev/null +++ b/tests/test_reading_ties.py @@ -0,0 +1,379 @@ +"""A row that the Ref tag and the Alt tag both explain through gaps, and how it is written. + +``row_decision`` takes the reading with fewer edits, then the one with fewer gap openings +(``_reading_cost``), and the Ref tag's only when the two are equal in that as well. Before, the Ref +tag's reading stood on every tie: an Alt haplotype with one insertion or deletion beside its target +was read as a Ref haplotype with two, or as a row whose target was deleted. + +A row read from the Alt tag is also written from that reading (``_read_from_alt``): its Variants are +its alignment to the Alt tag in the Ref tag's positions. Before, they were always its alignment to +the Ref tag, which could show the target unchanged or deleted on an AltMatch row. +""" + +import csv +import random +import sys +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO)) + +import madcats as mp # noqa: E402 + +BAND = 10 +# 0 1 2 3 4 5 6 7 8 +# 012345678901234567890123456789012345678901234567890123456789012345678901234567890 +REF = "GCTAAAGACAATTACATAACATACACGTCAGCACGAAACTTGATGGCCCAGTGTGAATCGCTTAAGGGTTAAGTAAGTGTG" +LEFT = 20 # bases of REF that are the left primer + + +def locus_at(target, alt_base, ref=REF): + """A marker on ``ref`` with its target at the 0-based ``target``.""" + return mp.Locus(0, "m1", ref[:LEFT], "", ref[target], alt_base, target, ref, ref[:target] + alt_base + ref[target + 1 :]) + + +def readings(locus, row): + """The gapped reading of ``row`` against the Ref tag and against the Alt tag, as row_decision compares them.""" + bound = min(mp.tag_mismatches(row, locus.ref_tag), mp.tag_mismatches(row, locus.alt_tag)) + return tuple(mp._unverified_gapped_reading(row, tag, BAND, bound) for tag in (locus.ref_tag, locus.alt_tag)) + + +def cell(locus, row, gap_band=BAND): + return mp.format_variants(mp.variant_events(locus, row, gap_band)) + + +def replay(ref, text, row): + """Rebuild a row from the Ref row and its Variants cell, by the rule the documentation gives. + + ``pos:REF>ALT`` replaces REF at POS by ALT (``.`` is no bases) and may not start on a Ref + base an earlier token used. ``clip=k`` and ``unresolved=k`` drop the last k Ref bases; + ``overhang=k`` then appends the row's last k bases, ``unresolved`` the rest of the row. + """ + out, cursor, drop, tail = "", 0, 0, None + for token in (token for token in text.split(";") if token not in ("", ".")): + if token.startswith("clip="): + drop = int(token[5:]) + elif token.startswith("overhang="): + tail = int(token[9:]) + elif token.startswith("unresolved="): + drop, tail = int(token[11:]), "rest" + else: + position, alleles = token.split(":") + removed, added = (allele.strip(".") for allele in alleles.split(">")) + start = int(position) - 1 + assert start >= cursor, f"two tokens use Ref base {position}: {text}" + assert ref[start : start + len(removed)] == removed, f"{token} does not name the Ref bases: {text}" + out += ref[cursor:start] + added + cursor = start + len(removed) + limit = len(ref) - drop + assert cursor <= limit, f"a token reaches into the bases the last one drops: {text}" + out += ref[cursor:limit] + if tail == "rest": + out += row[len(out) :] + elif tail: + out += row[len(row) - tail :] + return out + + +def shown_at(events, position): + """What a row's events put on a 1-based Ref position: the Ref base ("ref"), another base, or None (no base).""" + for kind, start, removed, added in events: + if kind == "snp" and start == position: + return added + if kind == "del": + first = start + 1 if added.strip(".") else start # an anchored deletion keeps its first base + if first <= position < start + len(removed.strip(".")): + return None + if kind in ("clip", "unresolved") and start <= position: + return None + return "ref" + + +def side_of(category, alt_base): + """What a category says stands on the target, in shown_at's terms; None for a category that names no allele.""" + return {"Ref": "ref", "RefMatch": "ref", "Alt": alt_base, "AltMatch": alt_base}.get(category) + + +def haplotypes(locus, count, seed): + """Ref and Alt haplotypes of a marker with one insertion or deletion, some with one more substitution. + + Half of the gaps lie within three bases of the target, where the two tags' readings tie most often; + inserted bases are copied from the neighbourhood half of the time, which makes repeats.""" + rng = random.Random(seed) + rows = set() + while len(rows) < count: + base = rng.choice([locus.ref_tag, locus.alt_tag]) + near = locus.variant_pos + rng.randint(-3, 4) + at = near if rng.random() < 0.5 else rng.randrange(LEFT + 2, len(base) - 14) + size = rng.randint(1, 6) + if rng.random() < 0.5: + row = base[:at] + base[at + size :] + "".join(rng.choice("ACGT") for _ in range(size)) + else: + piece = base[at : at + size] if rng.random() < 0.5 else "".join(rng.choice("ACGT") for _ in range(size)) + row = (base[:at] + piece + base[at:])[: len(base)] + if rng.random() < 0.3: + index = rng.randrange(LEFT, len(row)) + row = row[:index] + rng.choice([b for b in "ACGT" if b != row[index]]) + row[index + 1 :] + if row not in (locus.ref_tag, locus.alt_tag): + rows.add(row) + return sorted(rows) + + +class ReadingTieTests(unittest.TestCase): + def test_the_module_under_test_is_the_repository_s(self): + self.assertEqual(Path(mp.__file__).resolve().parent, REPO) + + def test_one_insertion_beside_the_alt_base_is_not_read_as_two_around_a_ref_base(self): + # The target is base 42, G in Ref and A in Alt, inside TGATG. An Alt haplotype (TAATG) that + # gained ATGATT after it reads TAATGATGATT: the Alt tag plus one insertion, or the Ref tag + # with TAA inserted before the T and ATT after the last G. Six inserted bases either way. + locus = locus_at(41, "A") + self.assertEqual((locus.ref_tag[40:45], locus.alt_tag[40:45]), ("TGATG", "TAATG")) + row = (locus.alt_tag[:45] + "ATGATT" + locus.alt_tag[45:])[: len(REF)] + self.assertEqual(row, (REF[:40] + "TAA" + REF[40:45] + "ATT" + REF[45:])[: len(REF)]) + on_ref, on_alt = readings(locus, row) + self.assertEqual((on_ref.edits, on_ref.gap_events), (6, 2)) + self.assertEqual((on_alt.edits, on_alt.gap_events), (6, 1)) + decision = mp.row_decision(locus, row, BAND) + self.assertIsNone(decision.unresolved) + self.assertEqual(decision.reading.gap_events, 1) + self.assertEqual(decision.reading.ref_to_read[41], 41) # the target is read where it stands + self.assertEqual(row[41], locus.alt_base) + self.assertEqual(mp.classify_sequence(locus, row, BAND), "AltMatch") + + def test_the_same_insertion_in_a_ref_haplotype_stays_with_the_ref_tag(self): + # The mirror marker: TAATG is the Ref tag and G the Alt base. The Ref tag's reading has the + # one insertion now, the Alt tag's the two. + ref = REF[:41] + "A" + REF[42:] + locus = locus_at(41, "G", ref) + row = (ref[:45] + "ATGATT" + ref[45:])[: len(ref)] + on_ref, on_alt = readings(locus, row) + self.assertEqual((on_ref.edits, on_ref.gap_events), (6, 1)) + self.assertEqual((on_alt.edits, on_alt.gap_events), (6, 2)) + self.assertEqual(mp.row_decision(locus, row, BAND).reading.gap_events, 1) + self.assertEqual(mp.classify_sequence(locus, row, BAND), "RefMatch") + + def test_one_deletion_after_the_alt_base_is_not_read_as_two_that_delete_the_target(self): + # The target is base 31, G in Ref and A in Alt, followed by CACG. An Alt haplotype without + # those four bases shows its A where the Ref tag has G C A: against the Ref tag the cheapest + # reading deletes G and C, keeps the A of CACG, and deletes C and G. Four deleted bases + # either way, in one piece against the Alt tag. + locus = locus_at(30, "A") + self.assertEqual(REF[30:35], "GCACG") + row = locus.alt_tag[:31] + locus.alt_tag[35:] + "ACGT" + on_ref, on_alt = readings(locus, row) + self.assertEqual((on_ref.edits, on_ref.gap_events), (4, 2)) + self.assertEqual((on_alt.edits, on_alt.gap_events), (4, 1)) + self.assertNotIn(30, on_ref.ref_to_read) # the Ref tag's reading deletes the target + decision = mp.row_decision(locus, row, BAND) + self.assertEqual(decision.reading.ref_to_read[30], 30) + self.assertEqual(mp.classify_sequence(locus, row, BAND), "AltMatch") + + def test_readings_equal_in_edits_and_openings_leave_the_ref_tag_s(self): + # With five bases gone (CACGA) the A that follows them is the Alt base again: the row is the + # Alt haplotype without CACGA and equally the Ref haplotype without GCACG. One deletion + # either way; no reading is better, and the Ref tag's has no base on the target. + locus = locus_at(30, "A") + row = locus.alt_tag[:31] + locus.alt_tag[36:] + "ACGTA" + self.assertEqual(row, REF[:30] + REF[35:] + "ACGTA") + on_ref, on_alt = readings(locus, row) + self.assertEqual((on_ref.edits, on_ref.gap_events), (5, 1)) + self.assertEqual((on_alt.edits, on_alt.gap_events), (5, 1)) + self.assertEqual(mp.row_decision(locus, row, BAND).reading.ops, on_ref.ops) + self.assertEqual(mp.classify_sequence(locus, row, BAND), "Other") + + def test_fewer_edits_come_before_fewer_openings(self): + def reading(edits, openings): + return mp.GappedReading(edits, 0, edits, openings, (), 0, 0, 0, {}) + + self.assertLess(mp._reading_cost(reading(5, 3)), mp._reading_cost(reading(6, 1))) + self.assertLess(mp._reading_cost(reading(6, 1)), mp._reading_cost(reading(6, 2))) + self.assertEqual(mp._reading_cost(reading(6, 2)), mp._reading_cost(reading(6, 2))) + + def test_rescue_off_reads_the_alt_base_at_the_fixed_offset(self): + # Without gapped readings there is nothing to tie: both rows show the Alt base on the target. + locus = locus_at(41, "A") + row = (locus.alt_tag[:45] + "ATGATT" + locus.alt_tag[45:])[: len(REF)] + self.assertEqual(mp.row_decision(locus, row, 0), mp.RowDecision(None, None)) + self.assertEqual(mp.classify_sequence(locus, row, 0), "AltMatch") + + +class VariantsFollowTheReadingTests(unittest.TestCase): + def test_insertion_beside_the_alt_base_is_written_as_one_insertion(self): + locus = locus_at(41, "A") + row = (locus.alt_tag[:45] + "ATGATT" + locus.alt_tag[45:])[: len(REF)] + self.assertTrue(mp._read_from_alt(locus, row, BAND)) + events = mp.variant_events(locus, row, BAND) + self.assertEqual(events, [("snp", 42, "G", "A"), ("ins", 45, "G", "GATGATT"), ("clip", 76, REF[75:], ".")]) + self.assertEqual(mp.format_variants(events), "42:G>A;45:G>GATGATT;clip=6") + self.assertEqual(replay(REF, "42:G>A;45:G>GATGATT;clip=6", row), row) + self.assertEqual(mp.marker_type_label(locus, row, BAND, events), "indel") + # The row's own alignment to the Ref tag, which was written before: two insertions and no Alt base. + self.assertEqual(mp.format_variants(mp._describe(REF, row, BAND, True)), "40:T>TTAA;45:G>GATT;clip=6") + + def test_gap_right_after_the_alt_base_is_written_without_an_anchor(self): + # The base before the gap is the target, and the row shows the Alt base there: the + # substitution uses that Ref base, so the gap starts on its own first base. + locus = locus_at(30, "A") + deleted = locus.alt_tag[:31] + locus.alt_tag[35:] + "ACGT" + events = mp.variant_events(locus, deleted, BAND) + self.assertEqual(events, [("snp", 31, "G", "A"), ("del", 32, "CACG", "."), ("overhang", 82, ".", "ACGT")]) + self.assertEqual(mp.format_variants(events), "31:G>A;32:CACG>.;overhang=4") + inserted = (locus.alt_tag[:31] + "TTT" + locus.alt_tag[31:])[: len(REF)] + self.assertEqual(mp.classify_sequence(locus, inserted, BAND), "AltMatch") + self.assertEqual(cell(locus, inserted), "31:G>A;32:.>TTT;clip=3") + for row in (deleted, inserted): + text = cell(locus, row) + self.assertEqual(replay(REF, text, row), row) + self.assertEqual(mp.parse_variants(text, REF, row), mp.variant_events(locus, row, BAND)) + self.assertEqual(mp.marker_type_label(locus, row, BAND), "indel") + + def test_a_row_read_from_the_ref_tag_is_written_as_before(self): + ref = REF[:41] + "A" + REF[42:] + locus = locus_at(41, "G", ref) + row = (ref[:45] + "ATGATT" + ref[45:])[: len(ref)] + self.assertFalse(mp._read_from_alt(locus, row, BAND)) + self.assertEqual(mp.variant_events(locus, row, BAND), mp._describe(ref, row, BAND, True)) + self.assertEqual(cell(locus, row), "45:G>GATGATT;clip=6") + + def test_marker_designed_as_an_indel_keeps_its_alignment_to_the_ref_tag(self): + alt = REF[:40] + REF[41:] + "A" + locus = mp.Locus(0, "m1", REF[:LEFT], "", REF[40], alt[40], 40, REF, alt) + row = alt[:60] + alt[62:] + "GT" + self.assertFalse(mp._read_from_alt(locus, row, BAND)) + self.assertEqual(mp.variant_events(locus, row, BAND), mp._describe(REF, row, BAND, True)) + + def test_variants_and_category_show_the_same_base_on_the_target(self): + # Every row is rebuilt from its Variants with no Ref base used twice, and its Variants put + # on the target what its category says: the Ref base, the Alt base, or no allele. + for target, alt_base, seed in ((41, "A", 1), (30, "A", 2), (55, "C", 3)): + locus = locus_at(target, alt_base) + read_from_alt = 0 + for row in haplotypes(locus, 500, seed): + category = mp.classify_sequence(locus, row, BAND) + events = mp.variant_events(locus, row, BAND) + text = mp.format_variants(events) + self.assertEqual(replay(REF, text, row), row, text) + self.assertEqual(mp.parse_variants(text, REF, row), events, text) + shown = shown_at(events, target + 1) + if side_of(category, alt_base) is not None: + self.assertEqual(shown, side_of(category, alt_base), (category, text)) + else: + self.assertNotIn(shown, ("ref", alt_base), (category, text)) + read_from_alt += mp._read_from_alt(locus, row, BAND) + self.assertGreater(read_from_alt, 50) + + +class TableTests(unittest.TestCase): + """The table ``generate`` writes for Alt haplotypes with a gap beside the target, with and without primers.""" + + def setUp(self): + self.loci = [ + mp.Locus(0, "inserted", REF[:LEFT], "", REF[41], "A", 41, REF, REF[:41] + "A" + REF[42:]), + mp.Locus(1, "deleted", REF[:LEFT], "", REF[30], "A", 30, REF, REF[:30] + "A" + REF[31:]), + ] + ins, dele = self.loci + self.row_inserted = (ins.alt_tag[:45] + "ATGATT" + ins.alt_tag[45:])[: len(REF)] + self.row_deleted = dele.alt_tag[:31] + dele.alt_tag[35:] + "ACGT" + self.rows = { + 0: {ins.ref_tag: 40, ins.alt_tag: 30, self.row_inserted: 12}, + 1: {dele.ref_tag: 40, dele.alt_tag: 30, self.row_deleted: 9}, + } + for index, locus in enumerate(self.loci): + for row in haplotypes(locus, 150, 10 + index): + self.rows[index].setdefault(row, 6) + + def write(self, directory, **options): + counts = {(index, tag): reads for index, rows in self.rows.items() for tag, reads in rows.items()} + results = [mp.SampleResult(mp.Sample("s0", "s0", "unused.fastq", {}), counts, {}, {}, {}, {})] + output = Path(directory) / "madc.csv" + mp.write_madc( + output, self.loci, results, mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0), + mp.OutputOptions(variants_path=output.with_suffix(".variants.csv"), **options), BAND, + ) + with open(output, newline="") as handle: + table = {(row["CloneID"], row["AlleleSequence"]): row for row in csv.DictReader(handle)} + with open(output.with_suffix(".variants.csv"), newline="") as handle: + sidecar = list(csv.DictReader(handle)) + return table, sidecar + + def check(self, table, shift): + """Every row is rebuilt from the marker's Ref row and its Variants, which show on the target what its category says.""" + checked = 0 + for locus in self.loci: + ref_row = next(seq for (marker, seq), row in table.items() if marker == locus.marker and row["AlleleID"].endswith("|Ref")) + for (marker, sequence), row in table.items(): + if marker != locus.marker: + continue + self.assertEqual(replay(ref_row, row["Variants"], sequence), sequence, row["Variants"]) + category = row["AlleleID"].split("|")[1].rstrip("_0123456789") + shown = shown_at(mp.parse_variants(row["Variants"], ref_row, sequence), locus.variant_pos - shift + 1) + if side_of(category, locus.alt_base) is not None: + self.assertEqual(shown, side_of(category, locus.alt_base), (category, row["Variants"])) + else: + self.assertNotIn(shown, ("ref", locus.alt_base), (category, row["Variants"])) + checked += 1 + return checked + + def test_table_with_primers(self): + with tempfile.TemporaryDirectory() as directory: + table, sidecar = self.write(directory) + inserted, deleted = table[("inserted", self.row_inserted)], table[("deleted", self.row_deleted)] + self.assertEqual((inserted["AlleleID"].split("_")[0], inserted["Variants"], inserted["MarkerType"]), ("inserted|AltMatch", "42:G>A;45:G>GATGATT;clip=6", "indel")) + self.assertEqual((deleted["AlleleID"].split("_")[0], deleted["Variants"], deleted["MarkerType"]), ("deleted|AltMatch", "31:G>A;32:CACG>.;overhang=4", "indel")) + gap = [row for row in sidecar if row["AlleleSequence"] == self.row_deleted and row["Type"] == "del"] + self.assertEqual([(row["Position"], row["Ref"], row["Alt"]) for row in gap], [("32", "CACG", ".")]) + self.assertGreater(self.check(table, 0), 300) + + def test_table_without_primers(self): + # The same reading in the rows as printed: positions count from the first base after the left primer. + with tempfile.TemporaryDirectory() as directory: + table, _ = self.write(directory, remove_primers=True) + inserted, deleted = table[("inserted", self.row_inserted[LEFT:])], table[("deleted", self.row_deleted[LEFT:])] + self.assertEqual((inserted["AlleleID"].split("_")[0], inserted["Variants"]), ("inserted|AltMatch", "22:G>A;25:G>GATGATT;clip=6")) + self.assertEqual((deleted["AlleleID"].split("_")[0], deleted["Variants"]), ("deleted|AltMatch", "11:G>A;12:CACG>.;overhang=4")) + self.assertGreater(self.check(table, LEFT), 300) + + +class PrimerCutTests(unittest.TestCase): + """Rows of a panel whose tags end with the first bases of the right primer, cut at that primer.""" + + def test_row_cut_at_its_primer_is_written_from_the_alt_tag_s_reading(self): + import test_remove_primers as primers + from unittest import mock + + checked = 0 + for seed in range(40): + rng = random.Random(seed) + left, insert, right = primers.dna(rng, primers.LEFT), primers.dna(rng, primers.INSERT), primers.dna(rng, primers.RIGHT) + target = primers.TARGET + alt_insert = primers.substituted(insert, target) + tag = lambda body: (left + body + right + primers.ADAPTER)[: primers.TAG] + locus = mp.Locus(0, "m", left, right, insert[target], alt_insert[target], primers.LEFT + target, tag(insert), tag(alt_insert)) + # An Alt haplotype without the three bases right after its target. + body = alt_insert[: target + 1] + alt_insert[target + 4 :] + row = tag(body) + category = mp.classify_sequence(locus, row, BAND) + if category != "AltMatch" or not mp._read_from_alt(locus, row, BAND): + continue + shown, rows, _, described = mp.trim_locus_rows( + locus, [(1, "Ref", locus.ref_tag), (2, "Alt", locus.alt_tag), (3, category, row)], + {locus.ref_tag: [5], locus.alt_tag: [5], row: [5]}, (primers.LEFT + primers.INSERT, right), BAND, mock.MagicMock(), + ) + self.assertEqual((shown.ref_tag, shown.alt_tag), (insert, alt_insert)) + self.assertIn(body, described) # cut at its primer: three bases shorter than the Ref row + self.assertEqual(described[body][3], alt_insert) + events = mp._describe(shown.ref_tag, body, BAND, *described[body]) + text = mp.format_variants(events) + self.assertEqual(replay(insert, text, body), body, text) + self.assertEqual(shown_at(events, target + 1), locus.alt_base, text) + self.assertEqual(events[0], ("snp", target + 1, insert[target], alt_insert[target]), text) + self.assertEqual(events[1], ("del", target + 2, insert[target + 1 : target + 4], "."), text) + checked += 1 + self.assertGreater(checked, 20) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_remove_primers.py b/tests/test_remove_primers.py new file mode 100644 index 0000000..99cb70d --- /dev/null +++ b/tests/test_remove_primers.py @@ -0,0 +1,749 @@ +"""Tests of ``generate --remove-primers on``: where the primers are, the cut in each row, and the table. + +The panels here are built the way a fixed-amplicon-length platform makes them: +every amplicon is left primer + insert + right primer, and a tag is its first +bases, so tags longer than left primer + insert end with the start of the +right primer. +""" +import csv +import random +import contextlib +import dataclasses +import io +import json +import tempfile +import unittest +from collections import Counter, defaultdict +from pathlib import Path +from unittest import mock + +import madcats as mp + +LEFT, INSERT, RIGHT = 20, 32, 18 # lengths of the three parts of an amplicon +TAG = 60 # so a Ref tag holds the first 8 bases of its right primer +TARGET = 10 # index of the target base in the insert +ADAPTER = "GATCGGAAGAGCACACGTCTGAACTCCAGTCAC" # what follows the right primer in a read +GAP_BAND = 10 +EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "madcats-demo" + + +def dna(rng, length): + return "".join(rng.choice("ACGT") for _ in range(length)) + + +def other_base(base): + return "ACGT"[("ACGT".index(base) + 1) % 4] + + +def substituted(sequence, index): + return sequence[:index] + other_base(sequence[index]) + sequence[index + 1 :] + + +def make_panel(markers=30, tag=TAG, seed=7, reverse=False): + """Loci plus, per marker, the parts its tags were cut from: (left primer, insert, right primer).""" + rng = random.Random(seed) + loci, parts = [], {} + for index in range(markers): + left, insert, right = dna(rng, LEFT), dna(rng, INSERT), dna(rng, RIGHT) + alt_insert = substituted(insert, TARGET) + marker = f"m{index:02d}" + parts[marker] = (left, insert, right) + loci.append( + mp.Locus( + index, marker, left, mp.reverse_complement(right) if reverse else right, + insert[TARGET], alt_insert[TARGET], LEFT + TARGET, + (left + insert + right + ADAPTER)[:tag], (left + alt_insert + right + ADAPTER)[:tag], + ) + ) + return loci, parts + + +def tag_of(parts, insert, tag=TAG, left=None, right=None): + """The tag a read of this insert gives: a fixed-length window of its amplicon.""" + return ((left or parts[0]) + insert + (right or parts[2]) + ADAPTER)[:tag] + + +def rebuild(ref, events): + """Apply a row's events to its Ref row; every event reads "replace REF at POS by ALT". + + Plain replay, left to right: an event that starts on a Ref base an earlier event already + used is an error, because a reader of the Variants column could not apply it either.""" + out, done = [], 0 + for kind, position, ref_allele, alt_allele in events: + start = position - 1 + if start < done: + raise AssertionError(f"two events use Ref base {position}: {mp.format_variants(events)}") + if kind == "clip": + out.append(ref[done:start]) + done = len(ref) + elif kind == "overhang": + out.append(ref[done:] + alt_allele) + done = len(ref) + elif kind == "unresolved": # the Ref bases from here on are not read: the row's own bases stand there + out.append(ref[done:start] + alt_allele) + done = len(ref) + else: + out.append(ref[done:start] + alt_allele.replace(".", "")) + done = start + len(ref_allele.replace(".", "")) + return "".join(out) + ref[done:] + + +class GeometryTests(unittest.TestCase): + def test_amplicon_length_is_read_from_the_tags(self): + loci, _ = make_panel() + self.assertEqual(mp.amplicon_geometry(loci), (LEFT + INSERT + RIGHT, False)) + site, reason = mp.right_primer_site(loci[0], mp.amplicon_geometry(loci)) + self.assertEqual((site, reason), ((LEFT + INSERT, loci[0].right_primer), "located")) + + def test_primers_listed_reverse_complemented(self): + loci, parts = make_panel(reverse=True) + geometry = mp.amplicon_geometry(loci) + self.assertEqual(geometry, (LEFT + INSERT + RIGHT, True)) + self.assertEqual(mp.right_primer_site(loci[3], geometry)[0], (LEFT + INSERT, parts["m03"][2])) + + def test_no_amplicon_length_without_enough_tags_that_reach_the_primer(self): + self.assertIsNone(mp.amplicon_geometry(make_panel(tag=LEFT + INSERT)[0])) # tags stop at the primer + self.assertIsNone(mp.amplicon_geometry(make_panel(markers=mp.AMPLICON_MIN_MARKERS - 1)[0])) + no_primers = [dataclasses.replace(locus, right_primer="") for locus in make_panel()[0]] + self.assertIsNone(mp.amplicon_geometry(no_primers)) + self.assertEqual(mp.right_primer_site(no_primers[0], None), (None, "no_right_primer")) + + def test_primer_past_the_tag_end_is_still_located(self): + loci, _ = make_panel() + geometry = mp.amplicon_geometry(loci) + short = dataclasses.replace(loci[0], ref_tag=loci[0].ref_tag[:45], alt_tag=loci[0].alt_tag[:45]) + self.assertEqual(mp.right_primer_site(short, geometry)[0][0], LEFT + INSERT) + + def test_marker_that_cannot_be_cut_is_not_located(self): + loci, parts = make_panel() + geometry = mp.amplicon_geometry(loci) + left, insert, right = parts["m00"] + # The tag's last bases are not the start of the primer the panel lists. + clash = dataclasses.replace(loci[0], right_primer=substituted(right, 2)) + self.assertEqual(mp.right_primer_site(clash, geometry), (None, "disagrees_with_amplicon_length")) + # The target lies where the primer starts. + in_primer = dataclasses.replace(loci[0], variant_pos=LEFT + INSERT) + self.assertEqual(mp.right_primer_site(in_primer, geometry), (None, "target_in_right_primer")) + # Without an amplicon length, only a primer that lies whole in the Ref tag is located. + self.assertEqual(mp.right_primer_site(loci[0], None), (None, "no_amplicon_length")) + whole = dataclasses.replace(loci[0], ref_tag=(left + insert[:22] + right + ADAPTER)[:TAG]) + self.assertEqual(mp.right_primer_site(whole, None), ((LEFT + 22, right), "located")) + # With one, such a tag does not read as the primer where the panel's length puts it: the + # marker's amplicon is another length, and its primer is the whole copy. + self.assertEqual(mp.right_primer_site(whole, geometry), ((LEFT + 22, right), "located")) + + def test_copy_of_the_primer_in_the_insert_is_not_the_primer(self): + loci, parts = make_panel() + geometry = mp.amplicon_geometry(loci) + left, insert, right = parts["m00"] + # The insert repeats the marker's right primer after the target. The tag still reads as the + # primer where the panel's amplicon length puts it, so that is the primer. + repeat = insert[: TARGET + 2] + right + insert[TARGET + 2 + RIGHT :] + tags = lambda length: { + "ref_tag": (left + repeat + right + ADAPTER)[:length], + "alt_tag": (left + substituted(repeat, TARGET) + right + ADAPTER)[:length], + } + for what, length in (("tag with 8 bases of the primer", TAG), ("tag that stops at the primer", LEFT + INSERT)): + with self.subTest(tag=what): + locus = dataclasses.replace(loci[0], **tags(length)) + site, reason = mp.right_primer_site(locus, geometry) + self.assertEqual((site, reason), ((LEFT + INSERT, right), "located")) + # No row is cut at the copy: every row keeps its insert. + for row_insert in (repeat, substituted(repeat, TARGET), substituted(repeat, 5)): + row = (left + row_insert + right + ADAPTER)[:length] + cut, kept = mp.right_primer_cut(locus, row, site, GAP_BAND) + self.assertEqual((row[LEFT:][:cut], kept), (row_insert, None)) + + +class CutTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.loci, cls.parts = make_panel() + cls.geometry = mp.amplicon_geometry(cls.loci) + + def trimmed(self, locus, row, site="panel"): + if site == "panel": + site = mp.right_primer_site(locus, self.geometry)[0] + cut, kept = mp.right_primer_cut(locus, row, site, GAP_BAND) + return row[len(locus.left_primer) :][:cut], kept + + def test_rows_are_cut_where_their_primer_begins(self): + for locus in self.loci[:10]: + parts = self.parts[locus.marker] + left, insert, right = parts + inserts = { + "the Ref tag": insert, + "a substitution": substituted(insert, 25), + "a deletion, which brings more of the primer in": insert[:18] + insert[21:], + "an insertion, which pushes the primer toward the end": insert[:18] + "TTG" + insert[18:], + "an insertion that pushes the primer out of the row": insert[:14] + "TTGACGTCA" + insert[14:], + } + for what, row_insert in inserts.items(): + with self.subTest(marker=locus.marker, row=what): + expected = row_insert[: TAG - LEFT] # the last case fills the row + self.assertEqual(self.trimmed(locus, tag_of(parts, row_insert)), (expected, None)) + with self.subTest(marker=locus.marker, row="substitutions in the primer copies"): + row = tag_of(parts, insert, left=substituted(left, 4), right=substituted(right, 1)) + self.assertEqual(self.trimmed(locus, row), (insert, None)) + + def test_indel_next_to_the_primer_is_read_from_the_primer(self): + # Four primer bases in the tag, and a primer whose third and fourth bases repeat its first two: + # an indel of two bases right before it costs the same as two substitutions. + left, insert, right = dna(random.Random(3), LEFT), "GCTTAGGCTAACCGGTTACTTAGCAGTTCAGT", "ACACGGTCTGAACTGGAT" + parts = (left, insert, right) + tag = LEFT + INSERT + 4 + locus = mp.Locus(0, "m", left, right, insert[TARGET], "T", LEFT + TARGET, tag_of(parts, insert, tag), + tag_of(parts, substituted(insert, TARGET), tag)) + site = (LEFT + INSERT, right) + deletion = tag_of(parts, insert[:-2], tag) + self.assertEqual(self.trimmed(locus, deletion, site), (insert[:-2], None)) + insertion = tag_of(parts, insert + "TG", tag) + self.assertEqual(self.trimmed(locus, insertion, site), (insert + "TG", None)) + self.assertEqual(self.trimmed(locus, locus.alt_tag, site), (substituted(insert, TARGET), None)) + + def test_short_product_is_found_without_a_site(self): + locus = self.loci[0] + parts = self.parts[locus.marker] + left, insert, right = parts + # The whole primer lies in the row, 17 bases earlier than the indel limit could explain. + self.assertEqual(self.trimmed(locus, tag_of(parts, insert[:15]), None), (insert[:15], None)) + self.assertEqual(self.trimmed(locus, tag_of(parts, insert[:15])), (insert[:15], None)) + # The same with the primer listed on the other strand. + flipped = dataclasses.replace(locus, right_primer=mp.reverse_complement(right)) + self.assertEqual(self.trimmed(flipped, tag_of(parts, insert[:15]), None), (insert[:15], None)) + # A row that ends in the first 10 bases of the primer, with no site to say so. + tail = (left + insert + right)[: LEFT + INSERT + mp.PRIMER_TAIL_UNLOCATED] + self.assertEqual(self.trimmed(locus, tail, None), (insert, None)) + # Nine bases could be chance there. With a site, eight are enough. + self.assertEqual(self.trimmed(locus, tail[:-1], None), (tail[LEFT:-1], None)) + elsewhere = (LEFT + INSERT + 14, right) # a site too far for the alignment to reach + self.assertEqual(self.trimmed(locus, tail[:-2], elsewhere), (insert, None)) + self.assertEqual(self.trimmed(locus, tail[:-3], elsewhere), (tail[LEFT:-3], None)) + + def test_degenerate_right_primer_is_found_whole(self): + # One marker, so no amplicon length: the primer is looked for itself, and the panel lists + # it with an N where the tag holds a base. + locus = self.loci[0] + left, insert, right = self.parts[locus.marker] + degenerate = dataclasses.replace( + locus, right_primer=right[:5] + "N" + right[6:], + ref_tag=(left + insert + right + ADAPTER)[:80], alt_tag=(left + substituted(insert, TARGET) + right + ADAPTER)[:80], + ) + site = mp.right_primer_site(degenerate, mp.amplicon_geometry([degenerate])) + self.assertEqual(site, ((LEFT + INSERT, degenerate.right_primer), "located")) + self.assertEqual(self.trimmed(degenerate, degenerate.ref_tag, site[0]), (insert, None)) + self.assertEqual(self.trimmed(degenerate, degenerate.ref_tag, None), (insert, None)) + flipped = dataclasses.replace(degenerate, right_primer=mp.reverse_complement(degenerate.right_primer)) + self.assertEqual(self.trimmed(flipped, flipped.ref_tag, None), (insert, None)) + + def test_canonical_rows_never_merge(self): + locus = self.loci[0] + rows = [(0, "Ref", locus.ref_tag), (1, "Alt", locus.alt_tag)] + counts = {locus.ref_tag: [3], locus.alt_tag: [4]} + tally = Counter() + with mock.patch.object(mp, "right_primer_cut", return_value=(TARGET - 2, None)): # a cut that loses the target + shown, trimmed, reads, _ = mp.trim_locus_rows(locus, rows, counts, None, GAP_BAND, tally) + self.assertEqual(tally["markers_right_primer_kept"], 1) + self.assertEqual((shown.ref_tag, shown.alt_tag), (locus.ref_tag[LEFT:], locus.alt_tag[LEFT:])) + self.assertEqual([row[1:] for row in trimmed], [("Ref", locus.ref_tag[LEFT:]), ("Alt", locus.alt_tag[LEFT:])]) + self.assertEqual(reads, {locus.ref_tag[LEFT:]: [3], locus.alt_tag[LEFT:]: [4]}) + + def test_row_keeps_its_primer_rather_than_lose_the_target_or_most_of_itself(self): + locus = self.loci[0] + parts = self.parts[locus.marker] + whole = lambda row: row[LEFT:] + before_target = tag_of(parts, parts[1][: TARGET - 2]) + self.assertEqual(self.trimmed(locus, before_target), (whole(before_target), "target")) + early_target = dataclasses.replace(locus, variant_pos=LEFT + 2) + few_bases = tag_of(parts, parts[1][: mp.TRIM_MIN_BASES - 1]) + self.assertEqual(self.trimmed(early_target, few_bases), (whole(few_bases), "short")) + + def test_row_keeps_the_base_its_category_was_read_from(self): + # A diverged haplotype: seven substitutions, and two bases missing shortly before the + # target, which is the last insert base but one. Seven substitutions are too many for a + # gapped reading, so the row is read at the fixed offsets. There its first primer base + # stands on the target, and that base is the Alt base. The alignment that finds the + # primer reads the deletion and places the target two bases earlier, so it would cut + # the primer off together with the base the category was read from. + rng = random.Random(2) + parts = left, insert, right = dna(rng, LEFT), dna(rng, INSERT), dna(rng, RIGHT) + target = INSERT - 2 + alt_insert = insert[:target] + right[0] + insert[target + 1 :] + locus = mp.Locus(0, "m", left, right, insert[target], right[0], LEFT + target, tag_of(parts, insert), tag_of(parts, alt_insert)) + diverged = insert + for index in range(1, 20, 3): + diverged = substituted(diverged, index) + row = tag_of(parts, diverged[:26] + diverged[28:]) + site = (LEFT + INSERT, right) + self.assertIsNone(mp.row_reading(locus, row, GAP_BAND)) + self.assertEqual(mp.classify_sequence(locus, row, GAP_BAND), "AltMatch") + self.assertTrue(right.startswith(row[LEFT + target :])) # the primer begins on the base that was read + self.assertEqual(self.trimmed(locus, row, site), (row[LEFT:], "target")) + # On a marker with its target elsewhere, the same row is cut where its primer begins. + early = dataclasses.replace(locus, variant_pos=LEFT + TARGET, alt_tag=tag_of(parts, substituted(insert, TARGET))) + self.assertEqual(self.trimmed(early, row, site), (row[LEFT : LEFT + INSERT - 2], None)) + + def test_row_that_ends_before_its_target_has_no_category_base(self): + # generate never writes such a row: a row is a whole tag. The functions still answer for + # one. It shows no base on the target, so it is Other and no primer is kept for it. + locus = self.loci[0] + short = locus.ref_tag[: locus.variant_pos] + for gap_band in (GAP_BAND, 0): + self.assertIsNone(mp.category_base(locus, short, gap_band)) + self.assertEqual(mp.classify_sequence(locus, short, gap_band), "Other") + self.assertEqual(self.trimmed(locus, short), (short[LEFT:], None)) + + +class DescriptionTests(unittest.TestCase): + """Events of rows of another length than their Ref row, as a table without primers has them.""" + + REF = "TTACGGATCCTTAGCATGCAAGTCGGATTACA" + + def events(self, row, whole=False): + locus = mp.Locus(0, "m", "", "", "G", "C", 5, self.REF, substituted(self.REF, 5)) + events = mp._describe(self.REF, row, GAP_BAND, mp._read_through_gaps(locus, row, GAP_BAND), whole) + if not whole: + self.assertEqual(events, mp.variant_events(locus, row, GAP_BAND)) + self.assertEqual(rebuild(self.REF, events), row) + self.assertEqual(mp.parse_variants(mp.format_variants(events), self.REF, row), events) + return mp.format_variants(events) + + def test_rows_of_another_length_are_aligned(self): + for whole in (False, True): + self.assertEqual(self.events(self.REF[:12] + self.REF[15:], whole), "12:TAGC>T") + self.assertEqual(self.events(self.REF[:12] + "GGA" + self.REF[12:], whole), "12:T>TGGA") + self.assertEqual(self.events(self.REF[:12] + self.REF[15:20] + "T" + self.REF[21:], whole), "12:TAGC>T;21:A>T") + + def test_end_of_a_row_cut_at_its_primer_is_an_indel_and_of_any_other_row_is_not_shown(self): + self.assertEqual(self.events(self.REF[:-2], whole=True), "29:TAC>T") # the last two bases, left-normalised + self.assertEqual(self.events(self.REF + "GT", whole=True), "32:A>AGT") + self.assertEqual(self.events(self.REF[:-2]), "clip=2") + self.assertEqual(self.events(self.REF + "GT"), "overhang=2") + # A deletion that brought in bases past the end of the Ref row. + self.assertEqual(self.events(self.REF[:12] + self.REF[15:] + "G"), "12:TAGC>T;overhang=1") + + def test_shared_end_is_never_inferred_from_the_lengths(self): + # Two tags of different lengths need not end at the same place: the shorter may be cut at + # its primer while an insertion pushed the primer out of the longer one. + self.assertEqual(mp._designed_events(self.REF, self.REF[:12] + self.REF[15:], GAP_BAND), (("del", 12, "TAGC", "T"),)) + self.assertEqual(mp.format_variants(mp._designed_events(self.REF, self.REF[:-2], GAP_BAND)), "clip=2") + pushed_out = self.REF[:12] + "GGACCTTGAC" + self.REF[12:-2] + self.assertEqual(mp.format_variants(mp._designed_events(self.REF, pushed_out, GAP_BAND)), "12:T>TGGACCTTGAC;clip=2") + + def test_gap_on_the_first_base_is_written_without_an_anchor(self): + for whole in (False, True): + self.assertEqual(self.events(self.REF[1:], whole), "1:T>.") + self.assertEqual(self.events("GG" + self.REF, whole), "1:.>GG") + # A change on the base after the gap is its own event. + self.assertEqual(self.events("C" + self.REF[2:], whole), "1:T>.;2:T>C") + + def test_no_two_events_use_the_same_ref_base(self): + # Each of these put two events on base 1, or on the base after a first-base deletion, when + # the gap was written from the base after it; replaying them repeated that base. + ref = self.REF + cases = { + "an insertion before base 1 and one after it": ("G" + ref[0] + "G" + ref[1:], "1:.>G;1:T>TG"), + "a longer insertion before base 1 and one after it": ("CAAC" + ref[0] + "GCC" + ref[1:], "1:.>CAAC;1:T>TGCC"), + "bases 1-2 deleted, then a deletion after base 3": (ref[2] + ref[4:], "1:TT>.;3:AC>A"), + } + for what, (row, expected) in cases.items(): + for whole in (False, True): + with self.subTest(case=what, whole=whole): + self.assertEqual(self.events(row, whole), expected) # events() replays them too + + def test_rows_too_different_in_length_are_compared_from_the_start(self): + short = self.REF[:14] + self.assertEqual(self.events(short), "clip=18") + self.assertEqual(self.events(substituted(short, 3)), f"4:C>{other_base('C')};clip=18") + self.assertEqual(self.events(self.REF + "ACGTACGTACGT"), "overhang=12") + + def test_rows_of_the_ref_length_are_described_as_before(self): + self.assertEqual(self.events(substituted(self.REF, 20)), "21:A>C") + self.assertEqual(self.events(self.REF[:8] + self.REF[11:] + "GGT"), "7:ATCC>A;overhang=3") + + +class TableTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.loci, cls.parts = make_panel() + + def write(self, rows_by_marker, remove_primers, directory, gap_band=GAP_BAND, **options): + """Write a two-sample table; ``rows_by_marker`` maps a marker to {tag: (reads, reads)}.""" + results = [] + index_of = {locus.marker: locus.index for locus in self.loci} + for sample in range(2): + counts = { + (index_of[marker], tag): reads[sample] + for marker, rows in rows_by_marker.items() + for tag, reads in rows.items() + if reads[sample] + } + results.append(mp.SampleResult(mp.Sample(f"s{sample}", f"s{sample}", "unused.fastq", {}), counts, {}, {}, {}, {})) + output = Path(directory) / f"madc_{'on' if remove_primers else 'off'}.csv" + rule = mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0) # a row needs 5 reads in one sample + summary = mp.write_madc( + output, self.loci, results, rule, + mp.OutputOptions(variants_path=output.with_suffix(".variants.csv"), remove_primers=remove_primers, **options), + gap_band, + ) + with open(output, newline="") as handle: + table = list(csv.DictReader(handle)) + return summary, table + + def test_table_without_primers(self): + locus = self.loci[0] + parts = self.parts[locus.marker] + left, insert, right = parts + alt_insert = substituted(insert, TARGET) + rows = { + locus.ref_tag: (40, 0), + locus.alt_tag: (0, 30), + tag_of(parts, insert, left=substituted(left, 3)): (7, 0), # a miscopied left primer + tag_of(parts, alt_insert, right=substituted(right, 2)): (0, 6), # a miscopied right primer + tag_of(parts, substituted(insert, 25)): (9, 8), + tag_of(parts, insert[:18] + insert[21:]): (5, 11), + } + with tempfile.TemporaryDirectory() as directory: + summary, table = self.write({locus.marker: rows}, True, directory) + _, untrimmed = self.write({locus.marker: rows}, False, directory) + marker_rows = [row for row in table if row["CloneID"] == locus.marker] + self.assertEqual(len([row for row in untrimmed if row["CloneID"] == locus.marker]), 6) + shown = [ + (row["AlleleID"].split("|")[1], row["AlleleSequence"], row["Variants"], row["MarkerType"], row["s0"], row["s1"]) + for row in marker_rows + ] + deleted = insert[:18] + insert[21:] + self.assertEqual( + sorted(shown), + sorted([ + ("Ref", insert, ".", ".", "47", "0"), + ("Alt", alt_insert, f"{TARGET + 1}:{insert[TARGET]}>{alt_insert[TARGET]}", "snp", "0", "36"), + ("RefMatch", substituted(insert, 25), f"26:{insert[25]}>{other_base(insert[25])}", "snp", "9", "8"), + ("RefMatch", deleted, mp.format_variants(mp._describe(insert, deleted, GAP_BAND, True)), "indel", "5", "11"), + ]), + ) + for row in marker_rows: + canonical = row["AlleleID"].endswith(("|Ref", "|Alt")) + self.assertEqual(row["ClusterConsensusSequence"], row["AlleleSequence"] if canonical else insert) + # Every marker's rows lose their primers, with or without reads. + for row in table: + if row["CloneID"] != locus.marker: + insert = self.parts[row["CloneID"]][1] + self.assertIn(row["AlleleSequence"], (insert, substituted(insert, TARGET))) + self.assertEqual( + summary["primer_removal"], + { + "amplicon_length": LEFT + INSERT + RIGHT, + "right_primers_reverse_complemented": False, + "markers_by_right_primer": {"located": len(self.loci)}, + "rows_merged": 2, + "rows_merged_across_allele_groups": 0, + "rows_right_primer_removed": 2 * len(self.loci) + 4, + "rows_right_primer_kept_target": 0, + "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) + self.assertEqual(summary["reads_in_emitted_rows"], sum(sum(reads) for reads in rows.values())) + + def variants_of(self, table, sequence): + return next(row["Variants"] for row in table if row["AlleleSequence"] == sequence) + + def test_known_target_alleles_and_events_before_and_after_primer_removal(self): + locus = self.loci[0] + parts = self.parts[locus.marker] + insert = parts[1] + # Fixed simulated truth: the target is G/T at full position 31, insert + # position 11. Expected events are literal Ref coordinates, independent + # of the aligner and annotation helpers being tested. + self.assertEqual(insert, "ATACACGTCAGCACGAAACTTGTTGGCCCAGT") + alt = substituted(insert, TARGET) + cases = [ + (insert[:4] + insert[6:], "RefMatch", "22:TAC>T;overhang=2", "2:TAC>T", "indel"), + (alt[:4] + alt[6:], "AltMatch", "22:TAC>T;31:G>T;overhang=2", "2:TAC>T;11:G>T", "indel"), + (insert[:4] + "AG" + insert[4:], "RefMatch", "24:C>CAG;clip=2", "4:C>CAG", "indel"), + (alt[:4] + "AG" + alt[4:], "AltMatch", "24:C>CAG;31:G>T;clip=2", "4:C>CAG;11:G>T", "indel"), + (insert[:10] + insert[11:], "Other", "30:AG>A;overhang=1", "10:AG>A", "indel"), + (alt[:17] + alt[19:], "AltMatch", "31:G>T;37:AAC>A;overhang=2", "11:G>T;17:AAC>A", "indel"), + (substituted(insert, 25), "RefMatch", "46:G>T", "26:G>T", "snp"), + ] + counts = {locus.ref_tag: (40, 0), locus.alt_tag: (0, 30)} + counts.update({tag_of(parts, row): (9, 11) for row, *_ in cases}) + with tempfile.TemporaryDirectory() as directory: + for trimmed in (False, True): + with self.subTest(remove_primers=trimmed): + summary, table = self.write({locus.marker: counts}, trimmed, directory) + by_sequence = {row["AlleleSequence"]: row for row in table if row["CloneID"] == locus.marker} + for insert_row, category, full_events, trimmed_events, marker_type in cases: + sequence = insert_row if trimmed else tag_of(parts, insert_row) + row = by_sequence[sequence] + self.assertEqual(row["AlleleID"], f"{locus.marker}|{category}") + self.assertEqual(row["Variants"], trimmed_events if trimmed else full_events) + self.assertEqual(row["MarkerType"], marker_type) + self.assertEqual((row["s0"], row["s1"]), ("9", "11")) + self.assertEqual(summary["reads_in_emitted_rows"], 70 + 20 * len(cases)) + if trimmed: + self.assertEqual(summary["primer_removal"]["rows_merged_across_allele_groups"], 0) + + def test_rescue_off_can_misclassify_an_indel_that_passes_assignment(self): + # A known Alt haplotype has an insertion upstream of its target. The + # base at the old offset happens to be Ref, despite passing the default + # 80% identity filter. Primer removal cannot repair this fixed-offset + # interpretation. Exercise all four switch combinations through FASTQ. + ref = "CCGTAATGCCTTTCCCTAACAGAGTTTTTCGAACTCGTGTTGTCGAGCGACGGAATTAGATCAGTTAAATGGCAGAAAACT" + target = 65 + alt = ref[:target] + "A" + ref[target + 1:] + indel = (alt[:60] + "C" + alt[60:])[:len(ref)] + self.assertEqual((ref[target], indel[target], indel[target + 1]), ("T", "T", "A")) + locus = mp.Locus(0, "late", ref[:20], "", "T", "A", target, ref, alt) + self.assertEqual(mp.select_marker(indel, [0], [locus], 16, gap_band=0), (0, "assigned")) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + tags = root / "tags.csv" + mp.write_reference_tags(tags, [locus]) + fastqs = root / "fastq" + fastqs.mkdir() + with (fastqs / "sample.fastq").open("w") as handle: + for number, sequence in enumerate([ref] * 40 + [alt] * 40 + [indel] * 40): + handle.write(f"@r{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + for rescue in ("on", "off"): + for trimmed in ("on", "off"): + with self.subTest(gapped_rescue=rescue, remove_primers=trimmed): + output = root / "madc.csv" + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + mp.main([ + "generate", "--fastq-dir", str(fastqs), "--reference-tags", str(tags), + "--output", str(output), "--jobs", "1", "--gapped-rescue", rescue, + "--remove-primers", trimmed, + ]) + with output.open(newline="") as handle: + rows = list(csv.DictReader(handle)) + row = next(row for row in rows if row["AlleleSequence"] == (indel[20:] if trimmed == "on" else indel)) + self.assertEqual(row["AlleleID"], "late|AltMatch" if rescue == "on" else "late|RefMatch") + self.assertEqual(row["sample"], "40") + self.assertEqual(sum(int(row["sample"]) for row in rows), 120) + if rescue == "on": + self.assertEqual(row["Variants"], "40:A>AC;46:T>A;clip=1" if trimmed == "on" else "60:A>AC;66:T>A;clip=1") + self.assertEqual(row["MarkerType"], "indel") + else: + self.assertEqual(row["MarkerType"], "snp") + self.assertNotIn("clip=", row["Variants"]) + self.assertNotIn("46:T>A" if trimmed == "on" else "66:T>A", row["Variants"]) + + def test_gapped_reading_of_the_full_tag_is_kept_after_the_primer_that_verified_it_is_cut(self): + # A deletion and an insertion of three bases each: the row keeps the Ref length. On the full + # tag the primer bases after the insertion verify the reading; the trimmed row has too few + # bases left to verify it again, so the decision made on the full tag is the one used. + locus = self.loci[0] + parts = self.parts[locus.marker] + insert = parts[1] + row_insert = insert[:12] + insert[15:21] + "TGA" + insert[21:] + tag = tag_of(parts, row_insert) + rows = {locus.marker: {locus.ref_tag: (40, 0), locus.alt_tag: (0, 30), tag: (9, 9)}} + with tempfile.TemporaryDirectory() as directory: + _, on = self.write(rows, True, directory) + _, off = self.write(rows, False, directory) + full = mp.variant_events(locus, tag, GAP_BAND) + self.assertEqual([event[0] for event in full], ["del", "ins"]) + self.assertEqual(self.variants_of(off, tag), mp.format_variants(full)) + moved = [(kind, position - LEFT, ref_allele, alt_allele) for kind, position, ref_allele, alt_allele in full] + self.assertEqual(self.variants_of(on, row_insert), mp.format_variants(moved)) + self.assertEqual(len(row_insert), INSERT) + + def test_designed_insertion_that_pushes_the_alt_primer_out_of_the_tag(self): + locus = self.loci[0] + parts = self.parts[locus.marker] + insert = parts[1] + alt_insert = insert[:TARGET] + "ACGTTGCAAT" + insert[TARGET:] + design = dataclasses.replace(locus, alt_tag=tag_of(parts, alt_insert), alt_base=alt_insert[TARGET]) + self.assertNotEqual(design.ref_base, design.alt_base) + loci = [design] + self.loci[1:] + results = [ + mp.SampleResult(mp.Sample(name, name, "unused.fastq", {}), counts, {}, {}, {}, {}) + for name, counts in (("s0", {(0, design.ref_tag): 40}), ("s1", {(0, design.alt_tag): 30})) + ] + with tempfile.TemporaryDirectory() as directory: + madc = Path(directory) / "madc.csv" + mp.write_madc(madc, loci, results, mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0), mp.OutputOptions(remove_primers=True), GAP_BAND) + with open(madc, newline="") as handle: + ref_row, alt_row = [row for row in csv.DictReader(handle) if row["CloneID"] == design.marker] + # The Ref row is cut at its primer; the Alt row fills the tag and stops two bases short of its own. + self.assertEqual(ref_row["AlleleSequence"], insert) + self.assertEqual(alt_row["AlleleSequence"], alt_insert[: TAG - LEFT]) + expected = mp.format_variants(mp._describe(insert, alt_insert[: TAG - LEFT], GAP_BAND, True)) + self.assertEqual((alt_row["Variants"], alt_row["MarkerType"]), (expected, "indel")) + self.assertRegex(alt_row["Variants"], r"^\d+:[ACGT]>[ACGT]{11};clip=2$") + self.assertIsNone(mp.events_either_way(insert, alt_insert[: TAG - LEFT], GAP_BAND)) + + def test_low_count_unresolved_row_cannot_poison_merged_clean_or_canonical_row(self): + left = "ACGTACGTACGTACGTACGT" + body = "GCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTATTTAAA" + right = "CCCGGGTTTAAACCCGGGT" + ref = left + body + right + alt = left + body[:15] + ("C" if body[15] != "C" else "G") + body[16:] + right + locus = mp.Locus(0, "m1", left, right, ref[35], alt[35], 35, ref, alt) + site = (len(left) + len(body), right) + clean_ins = ref[:40] + "A" + ref[40:80] + noisy_ins = ref[:40] + "A" + ref[40:72] + "T" + ref[72:79] + rows = [(0, "Ref", ref), (1, "Alt", alt), (2, "RefMatch", clean_ins), (2, "RefMatch", noisy_ins)] + counts = {ref: [100], alt: [100], clean_ins: [500], noisy_ins: [3]} + shown, _, trimmed_counts, readings = mp.trim_locus_rows(locus, rows, counts, site, GAP_BAND, Counter()) + trimmed = clean_ins[len(left) : len(left) + mp.right_primer_cut(locus, clean_ins, site, GAP_BAND)[0]] + self.assertEqual(trimmed_counts[trimmed], [503]) + self.assertIsNone(readings[trimmed][2]) + events = mp._describe(shown.ref_tag, trimmed, GAP_BAND, *readings[trimmed]) + self.assertEqual(mp.marker_type_label(shown, trimmed, GAP_BAND, events), "indel") + # Designed-indel marker: an Other row colliding with the canonical Alt row keeps its right primer + # while the canonical Alt row stays cleanly trimmed and uncorrupted. + alt_ins = ref[:35] + "A" + ref[35:80] + locus_di = mp.Locus(0, "m2", left, right, ref[35], "A", 35, ref, alt_ins) + noisy_alt = alt_ins[:72] + "T" + alt_ins[72:80] + tally_di = Counter() + shown_di, tr_di, trimmed_counts_di, readings_di = mp.trim_locus_rows( + locus_di, + [(0, "Ref", ref), (1, "Alt", alt_ins), (3, "AltMatch", noisy_alt)], + {ref: [100], alt_ins: [500], noisy_alt: [3]}, + site, + GAP_BAND, + tally_di, + ) + # Same allele group ("alt"): merges into canonical Alt cleanly without marking Alt unresolved. + self.assertEqual(trimmed_counts_di[shown_di.alt_tag], [503]) + self.assertIsNone(readings_di[shown_di.alt_tag][2]) + alt_events = mp._describe(shown_di.ref_tag, shown_di.alt_tag, GAP_BAND, *readings_di[shown_di.alt_tag]) + self.assertEqual(mp.marker_type_label(shown_di, shown_di.alt_tag, GAP_BAND, alt_events), "indel") + # Different allele groups (e.g. AltMatch and Other) that would become the same insert keep + # their right primer and stay two separate rows so no read changes allele group. + snp_body = body[:10] + ("A" if body[10] != "A" else "T") + body[11:] + 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)], + {ref: [100], alt: [100], s_alt: [15], s_other: [80]}, + 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) + self.assertEqual(args.remove_primers, "off") + mp._resolve_generate_defaults(args) + self.assertNotIn("remove_primers", mp._generate_provenance(args)) + args.remove_primers = "on" + self.assertIn(" remove_primers=on ", mp._generate_provenance(args)) + self.assertFalse(mp.OutputOptions().remove_primers) + locus = self.loci[0] + rows = {locus.marker: {locus.ref_tag: (40, 0), locus.alt_tag: (0, 30)}} + with tempfile.TemporaryDirectory() as directory: + summary, table = self.write(rows, False, directory) + self.assertNotIn("primer_removal", summary) + self.assertEqual(table[0]["AlleleSequence"], locus.ref_tag) + + @unittest.skipUnless(EXAMPLE.is_dir(), "example data not present") + def test_generate_refuses_a_table_without_primers_and_without_variants(self): + with tempfile.TemporaryDirectory() as directory: + tags, table = Path(directory) / "tags.csv", Path(directory) / "madc.csv" + arguments = ["generate", "--fastq-dir", str(EXAMPLE / "fastq"), "--reference-tags", str(tags), "--jobs", "1", + "--output", str(table), "--remove-primers", "on"] + captured = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(captured): + mp.main(["design", "--primers", str(EXAMPLE / "primers.csv"), "--probe-design", + str(EXAMPLE / "probe_design.tsv"), "--output", str(tags)]) + with self.assertRaises(SystemExit): + mp.main(arguments + ["--annotations", "off"]) + self.assertFalse(table.exists()) + self.assertIn("cannot be combined with --annotations off", captured.getvalue()) + mp.main(arguments) # annotations are on by default + with open(table, newline="") as handle: + self.assertIn("Variants", next(csv.reader(handle))) + self.assertIn("Removed primers:", captured.getvalue()) + + def test_every_row_rebuilds_from_its_ref_row_and_variants_and_no_read_changes_allele(self): + rng = random.Random(11) + rows_by_marker = {} + for locus in self.loci[:12]: + parts = self.parts[locus.marker] + rows = {locus.ref_tag: (rng.randint(5, 40), rng.randint(0, 40)), locus.alt_tag: (rng.randint(0, 40), rng.randint(5, 40))} + for _ in range(25): + insert = substituted(parts[1], TARGET) if rng.random() < 0.5 else parts[1] + for _ in range(rng.randint(0, 2)): + insert = substituted(insert, rng.randrange(INSERT)) + kind = rng.choice(("none", "none", "deletion", "insertion")) + at = rng.randrange(0, INSERT - 3) + size = rng.randint(1, 4) + if kind == "deletion": + insert = insert[:at] + insert[at + size :] + elif kind == "insertion": + insert = insert[:at] + dna(rng, size) + insert[at:] + left = substituted(parts[0], rng.randrange(LEFT)) if rng.random() < 0.2 else parts[0] + rows.setdefault(tag_of(parts, insert, left=left), (rng.randint(5, 30), rng.randint(0, 30))) + rows_by_marker[locus.marker] = rows + with tempfile.TemporaryDirectory() as directory: + summary, on = self.write(rows_by_marker, True, directory) + _, off = self.write(rows_by_marker, False, directory) + with open(Path(directory) / "madc_on.variants.csv", newline="") as handle: + sidecar = defaultdict(list) + for line in csv.DictReader(handle): + event = (line["Type"], int(line["Position"]), line["Ref"], line["Alt"]) + sidecar[(line["CloneID"], line["AlleleSequence"])].append(event) + ref_rows = {row["CloneID"]: row["AlleleSequence"] for row in on if row["AlleleID"].endswith("|Ref")} + for row in on: + events = sidecar[(row["CloneID"], row["AlleleSequence"])] + self.assertEqual(rebuild(ref_rows[row["CloneID"]], events), row["AlleleSequence"], row["Variants"]) + self.assertEqual(mp.format_variants(events), row["Variants"]) + # The Variants cell alone gives the events back. + self.assertEqual(mp.parse_variants(row["Variants"], ref_rows[row["CloneID"]], row["AlleleSequence"]), events) + + def reads_by_allele(table): + totals = defaultdict(int) + for row in table: + group = mp.ALLELE_GROUP[mp.allele_type(row["AlleleID"])] + for sample in ("s0", "s1"): + totals[(row["CloneID"], group, sample)] += int(row[sample]) + return totals + + self.assertEqual(summary["primer_removal"]["rows_merged_across_allele_groups"], 0) + self.assertEqual(reads_by_allele(on), reads_by_allele(off)) + self.assertGreater(summary["primer_removal"]["rows_merged"], 5) + self.assertLess(len(on), len(off)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_same_answers.py b/tests/test_same_answers.py new file mode 100644 index 0000000..d77a17b --- /dev/null +++ b/tests/test_same_answers.py @@ -0,0 +1,426 @@ +"""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 + 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; +- 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 +from unittest import mock + +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 + 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, locus.ref_tag, locus.alt_tag, budget)) + believed += got is not None + 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 panel(self, rng): + 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])) + 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)) + found += bool(fresh) + 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 = ( + 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 + + 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): + 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) + ) + # 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), ({}, {})) + self.assertEqual((without.counts, without.partial_counts, without.qc), (with_tallies.counts, with_tallies.partial_counts, with_tallies.qc)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_tiled_markers.py b/tests/test_tiled_markers.py new file mode 100644 index 0000000..f001a02 --- /dev/null +++ b/tests/test_tiled_markers.py @@ -0,0 +1,186 @@ +"""Tiled markers through ``generate`` and ``filter-paralogs``. + +Two markers that read the same tag window (tiles) share every read of their +amplicon. ``generate`` credits each read to both. The paralog filter must not +take one tile's rows for a copy of the other. + +The panel is written both ways a tile's tag can carry the other tile's +variant: as an ambiguity code, the way DArTag panels write it, and as the +reference base. +""" +import contextlib +import csv +import importlib.util +import io +import json +import random +import tempfile +import unittest +from pathlib import Path + +import madcats as mp + +HAS_MAPPY = importlib.util.find_spec("mappy") is not None + +TAG_LENGTH = 81 +SNP_A, SNP_B = 30, 55 # 0-based offsets of the two tiles' variants in the tag +AMBIGUITY_CODE = { + frozenset("AG"): "R", frozenset("CT"): "Y", frozenset("AC"): "M", + frozenset("GT"): "K", frozenset("AT"): "W", frozenset("CG"): "S", +} +# Each sample's two copies of the amplicon, as (base at tile A's variant, base at tile B's): +# r is the reference base, a the alternate. +SAMPLES = { + "s01": ("rr", "rr"), "s02": ("rr", "ar"), "s03": ("ar", "ar"), "s04": ("rr", "ra"), "s05": ("ra", "ra"), + "s06": ("ar", "ra"), "s07": ("rr", "aa"), "s08": ("aa", "aa"), "s09": ("ar", "aa"), "s10": ("ra", "aa"), +} +READS_PER_COPY = 30 + + +def with_base(sequence, offset, base): + return sequence[:offset] + base + sequence[offset + 1:] + + +def another_base(base): + return {"A": "C", "C": "T", "G": "A", "T": "G"}[base] + + +def run_quietly(arguments): + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + return mp.main([str(argument) for argument in arguments]) + + +def madc_rows(path): + with open(path, newline="") as handle: + rows = list(csv.reader(handle)) + header = next(index for index, row in enumerate(rows) if row and row[0] == "AlleleID") + first_sample = rows[header].index(next(iter(SAMPLES))) + return [(row[0], row[2], [int(value) for value in row[first_sample:]]) for row in rows[header + 1:]] + + +class TiledPanelTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.directory = tempfile.TemporaryDirectory() + cls.root = Path(cls.directory.name) + generator = random.Random(7) + genome = "".join(generator.choice("ACGT") for _ in range(20000)) + tag = genome[5000 : 5000 + TAG_LENGTH] + other_marker = genome[12000 : 12000 + TAG_LENGTH] + alternate_a, alternate_b = another_base(tag[SNP_A]), another_base(tag[SNP_B]) + (cls.root / "genome.fasta").write_text(">chr1\n" + genome + "\n") + cls.site = ("chr1", 5001, 5000 + TAG_LENGTH) + + copies = { + "rr": tag, + "ar": with_base(tag, SNP_A, alternate_a), + "ra": with_base(tag, SNP_B, alternate_b), + "aa": with_base(with_base(tag, SNP_A, alternate_a), SNP_B, alternate_b), + } + other_alternate = with_base(other_marker, 40, another_base(other_marker[40])) + fastq_dir = cls.root / "fastq" + fastq_dir.mkdir() + for sample, pair in SAMPLES.items(): + reads = [copies[copy] for copy in pair for _ in range(READS_PER_COPY)] + reads += [other_marker] * 20 + [other_alternate] * 20 + with (fastq_dir / f"{sample}.fastq").open("w") as handle: + for number, read in enumerate(reads): + handle.write(f"@{sample}_{number}\n{read}\n+\n{'I' * len(read)}\n") + cls.truth = { + "tileA": [sum(copy[0] == "a" for copy in pair) for pair in SAMPLES.values()], + "tileB": [sum(copy[1] == "a" for copy in pair) for pair in SAMPLES.values()], + } + + cls.madc = {} + for style in ("ambiguity codes", "reference bases"): + # Each tile's tags hold the other tile's variant as a code for both bases, or as the reference base. + at_b = AMBIGUITY_CODE[frozenset((tag[SNP_B], alternate_b))] if style == "ambiguity codes" else tag[SNP_B] + at_a = AMBIGUITY_CODE[frozenset((tag[SNP_A], alternate_a))] if style == "ambiguity codes" else tag[SNP_A] + ref_a, ref_b = with_base(tag, SNP_B, at_b), with_base(tag, SNP_A, at_a) + loci = [ + mp.Locus(0, "tileA", tag[:20], "", tag[SNP_A], alternate_a, SNP_A, ref_a, + with_base(ref_a, SNP_A, alternate_a)), + mp.Locus(1, "tileB", tag[:20], "", tag[SNP_B], alternate_b, SNP_B, ref_b, + with_base(ref_b, SNP_B, alternate_b)), + mp.Locus(2, "other", other_marker[:20], "", other_marker[40], other_alternate[40], 40, other_marker, + other_alternate), + ] + prefix = cls.root / style.replace(" ", "_") + mp.write_reference_tags(Path(str(prefix) + ".tags.csv"), loci) + cls.madc[style] = Path(str(prefix) + ".madc.csv") + exit_code = run_quietly([ + "generate", "--fastq-dir", fastq_dir, "--reference-tags", str(prefix) + ".tags.csv", + "--tag-length", TAG_LENGTH, "--jobs", 1, "--reproducible-min-samples", 0, "--depth-min-reads", 1, + "--cache-dir", str(prefix) + ".cache", "--output", cls.madc[style], + ]) + assert exit_code == 0 + + @classmethod + def tearDownClass(cls): + cls.directory.cleanup() + + def test_generate_gives_both_tiles_every_read_of_the_amplicon(self): + for style, madc in self.madc.items(): + with self.subTest(tags=style): + totals = {} + for allele_id, _, counts in madc_rows(madc): + marker = allele_id.split("|")[0] + totals[marker] = [total + count for total, count in zip(totals.get(marker, [0] * 10), counts)] + self.assertEqual(totals["tileA"], [2 * READS_PER_COPY] * len(SAMPLES)) + self.assertEqual(totals["tileB"], totals["tileA"]) + with open(str(madc) + ".qc.json") as handle: + self.assertEqual(json.load(handle)["tile_families"], [["tileA", "tileB"]]) + + def test_tags_with_ambiguity_codes_leave_the_ref_and_alt_rows_empty(self): + # No read can equal a tag that holds a code, so every read is on a RefMatch or + # AltMatch row. A genotype taken from the Ref and Alt rows alone would have no reads. + for allele_id, _, counts in madc_rows(self.madc["ambiguity codes"]): + if allele_id.startswith("tile") and allele_id.split("|")[1] in ("Ref", "Alt"): + self.assertEqual(sum(counts), 0, allele_id) + reads_on_match_rows = sum( + sum(counts) for allele_id, _, counts in madc_rows(self.madc["ambiguity codes"]) if "Match" in allele_id + ) + self.assertEqual(reads_on_match_rows, 2 * 2 * READS_PER_COPY * len(SAMPLES)) # both tiles, two copies each + + @unittest.skipUnless(HAS_MAPPY, "mappy not installed (pip install 'madcats[genome]')") + def test_paralog_filter_places_both_tiles_at_one_site_and_drops_nothing(self): + for style, madc in self.madc.items(): + with self.subTest(tags=style): + output = Path(str(madc) + ".filtered.csv") + self.assertEqual(run_quietly([ + "filter-paralogs", "--madc", madc, "--genome", self.root / "genome.fasta", "--output", output, + "--jobs", 1, + ]), 0) + with open(str(output) + ".genome_markers.csv", newline="") as handle: + sites = {row["CloneID"]: row["Sites"] for row in csv.DictReader(handle)} + contig, first, last = self.site + self.assertEqual(sites["tileA"], f"{contig}:{first}-{last}(+)") + self.assertEqual(sites["tileB"], sites["tileA"]) + with open(str(output) + ".genome_labels.csv", newline="") as handle: + labels = list(csv.DictReader(handle)) + self.assertEqual({row["Label"] for row in labels}, {"on_target"}) + self.assertEqual({row["Action"] for row in labels}, {"kept"}) + self.assertEqual(madc_rows(output), madc_rows(madc)) + + def test_auto_never_bridges_different_declared_groups_or_implicit_group_leaders(self): + base = "ACGTACGTACGTACGTACGTGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTAGCTATTTAAACCCGGGTTTAAACCCGGGT" + def tile(index, marker, pos, group=""): + alt = base[:pos] + ("T" if base[pos] != "T" else "A") + base[pos + 1 :] + return mp.Locus(index, marker, base[:20], "", base[pos], alt[pos], pos, base, alt, locus_group=group) + + for groups in (("g1", "", "g2"), ("g2", "", "g1"), ("g1", "g2", ""), ("", "g1", "g2")): + loci = [tile(i, f"m{i}", 30 + 10 * i, g) for i, g in enumerate(groups)] + self.assertEqual(mp.tile_families(loci, "auto"), (), groups) + # Same declared group separated by another declared group still links its own members. + loci = [tile(0, "m0", 30, "g1"), tile(1, "m1", 40, "g2"), tile(2, "m2", 50, "g1")] + self.assertEqual(mp.tile_families(loci, "auto"), ((0, 2),)) + # Leader marker whose LocusGroup cell is blank because another tile names it as its group + # (as write_reference_tags writes) belongs to that group and cannot link to another group. + leader = tile(0, "grpA", 30, "") + member = mp.Locus(1, "grpA__t2", "TTTTTTTTTTTTTTTTTTTT", "", "A", "C", 25, "T" * 81, "T" * 25 + "C" + "T" * 55, locus_group="grpA") + other_grp = tile(2, "grpB__t1", 50, "grpB") + self.assertEqual(mp.tile_families([leader, member, other_grp], "auto"), ()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_unresolved.py b/tests/test_unresolved.py new file mode 100644 index 0000000..6407b79 --- /dev/null +++ b/tests/test_unresolved.py @@ -0,0 +1,459 @@ +"""Tests of the unresolved end of a row. + +A gap near the end of a tag can explain a row with fewer edits than +substitutions and still have too few bases after it to be believed. Such a +row has two readings of its end. ``generate`` takes neither: the row is read +up to the first base the two readings disagree on, its Variants close with +``unresolved=k``, and a target in that stretch is ``Other``. These tests pin +that one decision where it is used: the category, the Variants and their +replay, the table with and without primers, and the pooled denoiser. +""" +import contextlib +import csv +import io +import json +import random +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO)) # the repository's modules, never an installed madcats +sys.path.insert(0, str(Path(__file__).resolve().parent)) # the helpers of test_remove_primers + +import madcats as mp # noqa: E402 + +BAND = 10 +# 0 1 2 3 4 5 6 7 8 +# 012345678901234567890123456789012345678901234567890123456789012345678901234567890 +REF = "GCTAAAGACAATTACATAACATACACGTCAGCACGAAACTTGTTGGCCCAGTGTGAATCGCTTAAGGGTTAAGTAAGTGTG" +LEFT = 20 # bases of REF that are the left primer + + +def locus_at(target, alt_base=None, index=0, marker="m1"): + """A marker on REF with its target at the 0-based ``target``.""" + alt_base = alt_base or next(base for base in "ACGT" if base != REF[target]) + return mp.Locus(index, marker, REF[:LEFT], "", REF[target], alt_base, target, REF, REF[:target] + alt_base + REF[target + 1 :]) + + +def cell(locus, row, gap_band=BAND): + return mp.format_variants(mp.variant_events(locus, row, gap_band)) + + +def replay(ref, text, row): + """Rebuild a row from the Ref row and its Variants cell, by the rule the documentation gives. + + ``pos:REF>ALT`` replaces REF at POS by ALT (``.`` is no bases) and may not start on a Ref + base an earlier token used. ``clip=k`` and ``unresolved=k`` drop the last k Ref bases; + ``overhang=k`` then appends the row's last k bases, ``unresolved`` the rest of the row. + """ + out, cursor, drop, tail = "", 0, 0, None + for token in (token for token in text.split(";") if token not in ("", ".")): + if token.startswith("clip="): + drop = int(token[5:]) + elif token.startswith("overhang="): + tail = int(token[9:]) + elif token.startswith("unresolved="): + drop, tail = int(token[11:]), "rest" + else: + position, alleles = token.split(":") + removed, added = (allele.strip(".") for allele in alleles.split(">")) + start = int(position) - 1 + assert start >= cursor, f"two tokens use Ref base {position}: {text}" + assert ref[start : start + len(removed)] == removed, f"{token} does not name the Ref bases: {text}" + out += ref[cursor:start] + added + cursor = start + len(removed) + limit = len(ref) - drop + assert cursor <= limit, f"a token reaches into the bases the last one drops: {text}" + out += ref[cursor:limit] + if tail == "rest": + out += row[len(out) :] + elif tail: + out += row[len(row) - tail :] + return out + + +# A Ref haplotype that lost base 71 (0-based 70), with one more base of its amplicon at the end. +ONE_BASE_DELETION = REF[:70] + REF[71:] + "C" +# One that lost bases 73 and 74 (0-based 72 and 73). +TWO_BASE_DELETION = REF[:72] + REF[74:] + "GT" +# A verified two-base deletion after base 25, then one inserted base near the end. +DELETION_THEN_LATE_GAP = "GCTAAAGACAATTACATAACATACATCAGCACGAAACTTGTTGGCCCAGTGTGAATCGCTTAAGGGTTCAGGTAAGTGTGT" + + +class DecisionTests(unittest.TestCase): + def test_the_modules_under_test_are_the_repository_s(self): + self.assertEqual(Path(mp.__file__).resolve().parent, REPO) + + def test_target_before_the_unread_end_keeps_its_category(self): + locus = locus_at(40) + # Nine bases follow the deletion, three fewer than a gapped reading needs. The gap costs + # two edits and substitutions six, so the row's end has two readings and is not read. + self.assertEqual(mp.tag_mismatches(TWO_BASE_DELETION, REF), 6) + decision = mp.row_decision(locus, TWO_BASE_DELETION, BAND) + self.assertIsNone(decision.reading) + self.assertEqual(decision.unresolved, (72, 72)) + # The target, base 41, is read where both readings put it. + self.assertEqual(mp.classify_sequence(locus, TWO_BASE_DELETION, BAND), "RefMatch") + events = mp.variant_events(locus, TWO_BASE_DELETION, BAND) + self.assertEqual(events, [("unresolved", 73, REF[72:], TWO_BASE_DELETION[72:])]) + self.assertEqual(mp.format_variants(events), "unresolved=9") + self.assertEqual(mp.marker_type_label(locus, TWO_BASE_DELETION, BAND, events), "unresolved") + + def test_target_in_the_unread_end_is_other(self): + # The target is base 77. The deletion moves base 78, a T, onto it, and T is the Alt allele: + # read at the fixed offset this Ref haplotype is an Alt allele, read through the gap it is + # a Ref allele. Ten bases follow the gap, so neither reading is taken. + locus = locus_at(76, alt_base="T") + self.assertEqual((REF[76], REF[77]), ("G", "T")) + self.assertEqual(ONE_BASE_DELETION[76], locus.alt_base) + self.assertEqual(mp.row_decision(locus, ONE_BASE_DELETION, BAND).unresolved, (71, 71)) + self.assertEqual(mp.classify_sequence(locus, ONE_BASE_DELETION, BAND), "Other") + self.assertEqual(cell(locus, ONE_BASE_DELETION), "unresolved=10") + # What each reading alone would say: without gapped readings, the Alt allele ... + self.assertEqual(mp.classify_sequence(locus, ONE_BASE_DELETION, 0), "AltMatch") + # ... and with every cheaper gapped reading believed, the Ref allele. + with mock.patch.object(mp, "GAP_VERIFIED_SUFFIX", 0): + self.assertEqual(mp.classify_sequence(locus, ONE_BASE_DELETION, BAND), "RefMatch") + self.assertEqual(cell(locus, ONE_BASE_DELETION), "70:TA>T;overhang=1") + + def test_a_gap_with_enough_bases_after_it_is_read_as_before(self): + locus = locus_at(76, alt_base="T") + row = locus.alt_tag[:30] + locus.alt_tag[32:] + "GT" # an Alt haplotype without bases 31 and 32 + decision = mp.row_decision(locus, row, BAND) + self.assertIsNotNone(decision.reading) + self.assertIsNone(decision.unresolved) + self.assertEqual(mp.classify_sequence(locus, row, BAND), "AltMatch") + self.assertEqual(cell(locus, row), "30:AGC>A;77:G>T;overhang=2") + + def test_substitutions_near_the_end_stay_substitutions(self): + locus = locus_at(40) + row = REF[:78] + "A" + REF[79:] + self.assertEqual(mp.row_decision(locus, row, BAND), mp.RowDecision(None, None)) + self.assertEqual(cell(locus, row), "79:G>A") + self.assertEqual(mp.marker_type_label(locus, row, BAND), "snp") + + def test_a_verified_gap_before_the_unread_end_is_kept(self): + # Against the Alt tag the row is the two-base deletion alone, verified; against the Ref tag + # a second gap near the end is cheaper. The two agree up to base 70: the deletion is + # written, the rest is not read, and the row's 11 last bases stand for the Ref row's 11. + locus = locus_at(70) + decision = mp.row_decision(locus, DELETION_THEN_LATE_GAP, BAND) + self.assertIsNotNone(decision.reading) + self.assertEqual(decision.unresolved, (70, 68)) + self.assertEqual(mp.classify_sequence(locus, DELETION_THEN_LATE_GAP, BAND), "Other") + events = mp.variant_events(locus, DELETION_THEN_LATE_GAP, BAND) + self.assertEqual( + events, [("del", 25, "ACG", "A"), ("unresolved", 71, REF[70:], DELETION_THEN_LATE_GAP[68:])] + ) + self.assertEqual(mp.format_variants(events), "25:ACG>A;unresolved=11") + self.assertEqual(replay(REF, "25:ACG>A;unresolved=11", DELETION_THEN_LATE_GAP), DELETION_THEN_LATE_GAP) + # A target before the stretch is read through the verified deletion. + earlier = locus_at(40) + self.assertEqual(mp.classify_sequence(earlier, DELETION_THEN_LATE_GAP, BAND), "RefMatch") + + def test_a_verified_early_indel_survives_a_late_unverified_indel_on_the_same_template(self): + # A 1-bp insertion at base 40 (verified by 32 clean bases) plus an unverified 1-bp insertion + # at base 72 must keep the verified insertion and leave only the late tail unresolved. + locus = locus_at(55) + row = REF[:40] + "A" + REF[40:72] + "T" + REF[72:79] + decision = mp.row_decision(locus, row, BAND) + self.assertIsNotNone(decision.reading) + self.assertIsNotNone(decision.unresolved) + self.assertGreaterEqual(decision.unresolved[0], 70) + self.assertEqual(mp.classify_sequence(locus, row, BAND), "RefMatch") + events = mp.variant_events(locus, row, BAND) + text = mp.format_variants(events) + self.assertIn("ins", [kind for kind, *_ in events]) + self.assertTrue(text.endswith(f"unresolved={len(REF) - decision.unresolved[0]}"), text) + self.assertEqual(replay(REF, text, row), row) + self.assertEqual(mp.parse_variants(text, REF, row), events) + # An early gap followed by >2 mismatches in its 12 verifying bases is rejected (e.g. adapter/noise). + dirty = list(row) + for pos in (43, 46, 49): + dirty[pos] = "C" if dirty[pos] != "C" else "G" + dirty_row = "".join(dirty) + self.assertIsNone(mp.row_decision(locus, dirty_row, BAND).reading) + + def test_canonical_rows_and_rescue_off_have_nothing_unresolved(self): + locus = locus_at(76, alt_base="T") + for row in (locus.ref_tag, locus.alt_tag): + self.assertEqual(mp.row_decision(locus, row, BAND), mp.RowDecision(None, None)) + self.assertEqual(mp.row_decision(locus, ONE_BASE_DELETION, 0), mp.RowDecision(None, None)) + self.assertNotIn("unresolved", cell(locus, ONE_BASE_DELETION, 0)) + + def test_marker_designed_as_an_indel_marks_the_unread_end_in_ref_coordinates(self): + # The Alt tag lacks base 41, so every row is written through gaps against the Ref tag. + # A designed deletion does not settle a second gap near the row's end: that end is + # unread on such a marker too, counted on the Ref tag whichever tag the row was read from. + alt = REF[:40] + REF[41:] + "A" + locus = mp.Locus(0, "m1", REF[:LEFT], "", REF[40], alt[40], 40, REF, alt) + self.assertEqual(mp.format_variants(mp._designed_events(REF, alt, BAND)), "39:CT>C;overhang=1") + # A Ref haplotype without bases 73 and 74. + self.assertEqual(mp.unresolved_end(locus, TWO_BASE_DELETION, BAND), (72, 72)) + self.assertEqual(cell(locus, TWO_BASE_DELETION), "unresolved=9") + # The same two bases missing from an Alt haplotype: Alt base 72 is Ref base 73. + on_alt = alt[:71] + alt[73:] + "GT" + self.assertEqual(mp.row_decision(locus, on_alt, BAND).unresolved, (71, 71)) + self.assertEqual(mp.unresolved_end(locus, on_alt, BAND), (72, 71)) + self.assertEqual(cell(locus, on_alt), "39:CT>C;unresolved=9") + self.assertEqual(mp.classify_sequence(locus, on_alt, BAND), "AltMatch") # the target lies before it + for row in (TWO_BASE_DELETION, on_alt): + events = mp.variant_events(locus, row, BAND) + self.assertEqual(replay(REF, mp.format_variants(events), row), row) + self.assertEqual(mp.parse_variants(mp.format_variants(events), REF, row), events) + + +class VariantsCellTests(unittest.TestCase): + def rows(self): + """Ref and Alt haplotypes with zero or one gap well inside, then an edit in the last 15 bases.""" + rng = random.Random(5) + locus = locus_at(70) + rows = set() + while len(rows) < 600: + row = rng.choice([locus.ref_tag, locus.alt_tag]) + if rng.random() < 0.5: + cut, lost = rng.randrange(22, 50), rng.randrange(1, 4) + row = row[:cut] + row[cut + lost :] + "".join(rng.choice("ACGT") for _ in range(lost)) + for _ in range(rng.randrange(1, 3)): + at, kind = rng.randrange(66, 81), rng.choice("sdi") + if kind == "s": + row = row[:at] + rng.choice("ACGT") + row[at + 1 :] + elif kind == "d": + row = row[:at] + row[at + 1 :] + rng.choice("ACGT") + else: + row = (row[:at] + rng.choice("ACGT") + row[at:])[:81] + if row not in (locus.ref_tag, locus.alt_tag): + rows.add(row) + return locus, sorted(rows) + + def test_every_row_is_rebuilt_from_its_cell_and_the_cell_parses_back(self): + locus, rows = self.rows() + unresolved = after_a_gap = 0 + for row in rows: + events = mp.variant_events(locus, row, BAND) + text = mp.format_variants(events) + self.assertEqual(replay(REF, text, row), row, text) + self.assertEqual(mp.parse_variants(text, REF, row), events, text) + if "unresolved=" in text: + unresolved += 1 + after_a_gap += len(text.split(";")) > 1 and mp.row_decision(locus, row, BAND).reading is not None + self.assertTrue(text.split(";")[-1].startswith("unresolved="), text) + self.assertEqual(mp.marker_type_label(locus, row, BAND, events), "unresolved") + # The rows do exercise the outcome, with and without a verified gap before it. + self.assertGreater(unresolved, 100) + self.assertGreater(after_a_gap, 10) + + def test_category_and_cell_agree_about_the_target(self): + # A target at or after the first Ref base not read is Other; one before it is read. + _, rows = self.rows() + for target in (40, 70, 76): + locus = locus_at(target) + for row in rows: + stretch = mp.row_decision(locus, row, BAND).unresolved + if stretch is not None and target >= stretch[0]: + self.assertEqual(mp.classify_sequence(locus, row, BAND), "Other") + + def test_the_token_counts_ref_bases_from_the_end(self): + events = mp.parse_variants("25:ACG>A;unresolved=11", REF, DELETION_THEN_LATE_GAP) + self.assertEqual(events[-1], ("unresolved", 71, REF[70:], DELETION_THEN_LATE_GAP[68:])) + self.assertEqual( + mp.parse_variants("unresolved=9", REF, TWO_BASE_DELETION), [("unresolved", 73, REF[72:], TWO_BASE_DELETION[72:])] + ) + + def test_a_token_this_version_does_not_know_is_an_error(self): + for text in ("79:G>A;someday=3", "unresolved=200", "unresolved=x"): + with self.assertRaises(ValueError, msg=text): + mp.parse_variants(text, REF, TWO_BASE_DELETION) + + +class TableTests(unittest.TestCase): + """The table ``generate`` writes: two markers on REF, one row with an unread end at each.""" + + def setUp(self): + self.before = locus_at(40, index=0, marker="before") # target before the unread end + self.inside = locus_at(76, alt_base="T", index=1, marker="inside") # target inside it + self.loci = [self.before, self.inside] + self.rows = { + 0: {self.before.ref_tag: (40, 0), self.before.alt_tag: (0, 30), TWO_BASE_DELETION: (9, 11)}, + 1: {self.inside.ref_tag: (40, 0), self.inside.alt_tag: (0, 30), ONE_BASE_DELETION: (7, 6)}, + } + + def write(self, directory, **options): + results = [] + for sample in range(2): + counts = {(index, tag): reads[sample] for index, rows in self.rows.items() for tag, reads in rows.items() if reads[sample]} + results.append(mp.SampleResult(mp.Sample(f"s{sample}", f"s{sample}", "unused.fastq", {}), counts, {}, {}, {}, {})) + output = Path(directory) / "madc.csv" + summary = mp.write_madc( + output, self.loci, results, mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0), + mp.OutputOptions(variants_path=output.with_suffix(".variants.csv"), **options), BAND, + ) + with open(output, newline="") as handle: + table = {(row["CloneID"], row["AlleleSequence"]): row for row in csv.DictReader(handle)} + sidecar = [] + if output.with_suffix(".variants.csv").exists(): + with open(output.with_suffix(".variants.csv"), newline="") as handle: + sidecar = [row for row in csv.DictReader(handle) if row["Type"] == "unresolved"] + return summary, table, sidecar + + TALLY = {"rows": 2, "reads": 33, "rows_target_not_read": 1, "reads_target_not_read": 13} + + def test_table_with_primers(self): + with tempfile.TemporaryDirectory() as directory: + summary, table, sidecar = self.write(directory) + before, inside = table[("before", TWO_BASE_DELETION)], table[("inside", ONE_BASE_DELETION)] + self.assertEqual((before["AlleleID"], before["Variants"], before["MarkerType"]), ("before|RefMatch", "unresolved=9", "unresolved")) + self.assertEqual((inside["AlleleID"], inside["Variants"], inside["MarkerType"]), ("inside|Other", "unresolved=10", "unresolved")) + self.assertEqual((before["s0"], before["s1"], inside["s0"], inside["s1"]), ("9", "11", "7", "6")) + self.assertEqual( + [(row["CloneID"], row["Position"], row["Ref"], row["Alt"]) for row in sidecar], + [("before", "73", REF[72:], TWO_BASE_DELETION[72:]), ("inside", "72", REF[71:], ONE_BASE_DELETION[71:])], + ) + self.assertEqual(summary["unresolved_ends"], self.TALLY) + self.assertEqual(summary["variants"]["events"], {"snp": 2, "unresolved": 2}) + self.assertEqual(summary["marker_types"]["unresolved"], 2) + self.assertEqual(summary["categories"], {"Ref": 2, "Alt": 2, "RefMatch": 1, "Other": 1}) + + def test_table_without_annotations_has_the_same_categories_and_tally(self): + with tempfile.TemporaryDirectory() as directory: + summary, table, sidecar = self.write(directory, annotations=False) + self.assertEqual(table[("before", TWO_BASE_DELETION)]["AlleleID"], "before|RefMatch") + self.assertEqual(table[("inside", ONE_BASE_DELETION)]["AlleleID"], "inside|Other") + self.assertEqual(summary["unresolved_ends"], self.TALLY) + self.assertEqual(sidecar, []) + + def test_table_without_primers_carries_the_decision(self): + # The same decision in the frame of the rows as printed: the categories and the token are + # those of the full tags, positions count from the first base after the left primer. + with tempfile.TemporaryDirectory() as directory: + summary, table, sidecar = self.write(directory, remove_primers=True) + before, inside = table[("before", TWO_BASE_DELETION[LEFT:])], table[("inside", ONE_BASE_DELETION[LEFT:])] + self.assertEqual((before["AlleleID"], before["Variants"], before["MarkerType"]), ("before|RefMatch", "unresolved=9", "unresolved")) + self.assertEqual((inside["AlleleID"], inside["Variants"], inside["MarkerType"]), ("inside|Other", "unresolved=10", "unresolved")) + self.assertEqual( + [(row["CloneID"], row["Position"], row["Ref"], row["Alt"]) for row in sidecar], + [("before", "53", REF[72:], TWO_BASE_DELETION[72:]), ("inside", "52", REF[71:], ONE_BASE_DELETION[71:])], + ) + for (marker, sequence), row in table.items(): + ref_row = next(shown for (other, shown), entry in table.items() if other == marker and entry["AlleleID"].endswith("|Ref")) + self.assertEqual(replay(ref_row, row["Variants"], sequence), sequence) + self.assertEqual(summary["unresolved_ends"], self.TALLY) + + def test_gapped_rescue_off_writes_no_unresolved_row(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "madc.csv" + results = [mp.SampleResult(mp.Sample("s0", "s0", "unused.fastq", {}), {(1, ONE_BASE_DELETION): 9}, {}, {}, {}, {})] + summary = mp.write_madc(output, self.loci, results, mp.EvidenceRule(1, 20, 0, 0, 0, 5, 0.0), mp.OutputOptions(), 0) + self.assertEqual(summary["unresolved_ends"]["rows"], 0) + self.assertNotIn("unresolved", summary["variants"]["events"]) + + +class PrimerCutTests(unittest.TestCase): + """Rows of a panel whose tags end with the first bases of the right primer.""" + + def trimmed_row(self, target): + """A marker with its target at this insert base, and a row without insert bases 30 and 31. + + One insert base and ten primer bases follow the gap on the full tag, so the row's end is + unread from insert base 30. The row's primer is found two bases early and cut off, which + leaves the row two bases shorter than the Ref row.""" + import test_remove_primers as primers + + rng = random.Random(11) + left, insert, right = primers.dna(rng, primers.LEFT), primers.dna(rng, primers.INSERT), primers.dna(rng, primers.RIGHT) + alt_insert = primers.substituted(insert, target) + tag = lambda body: (left + body + right + primers.ADAPTER)[: primers.TAG] + locus = mp.Locus(0, "m", left, right, insert[target], alt_insert[target], primers.LEFT + target, tag(insert), tag(alt_insert)) + row = tag(insert[:29] + insert[31:]) + self.assertEqual(mp.unresolved_end(locus, row, BAND), (49, 49)) + category = mp.classify_sequence(locus, row, BAND) + shown, _, _, readings = mp.trim_locus_rows( + locus, [(1, "Ref", locus.ref_tag), (2, "Alt", locus.alt_tag), (3, category, row)], + {locus.ref_tag: [5], locus.alt_tag: [5], row: [5]}, (primers.LEFT + primers.INSERT, right), BAND, mock.MagicMock(), + ) + trimmed = insert[:29] + insert[31:] + self.assertEqual((len(shown.ref_tag), len(trimmed)), (32, 30)) + self.assertIn(trimmed, readings) + text = mp.format_variants(mp._describe(shown.ref_tag, trimmed, BAND, *readings[trimmed])) + self.assertEqual(replay(shown.ref_tag, text, trimmed), trimmed) + return category, readings[trimmed], text + + def test_row_cut_at_its_primer_to_another_length_keeps_its_unread_end(self): + # The target, insert base 11, is read: the category stands. The row's other length shows + # that something is missing, but not which reading of its end was right, so the end stays + # unread in the row as printed: the last three Ref bases, where one base of the row stands. + category, reading, text = self.trimmed_row(target=10) + self.assertEqual(category, "RefMatch") + self.assertEqual(reading[2], (29, 29)) + self.assertEqual(text, "unresolved=3") + + def test_row_that_is_other_for_an_unread_target_never_shows_a_reading_of_it(self): + # The target is the last insert base, inside the unread end: the row is Other. Cut at + # its primer, the row must not be written through a deletion that puts a base on it. + category, reading, text = self.trimmed_row(target=31) + self.assertEqual(category, "Other") + self.assertEqual(text, "unresolved=3") + + +class PooledDenoiserTests(unittest.TestCase): + def test_row_with_an_unread_target_is_not_folded_into_an_allele(self): + # The row sits one base closer to the Alt tag than to the Ref tag, because the shifted + # base at the target is the Alt allele. Read at the fixed offset it was an Alt-allele row + # and the pooled pass could fold its reads into the Alt row. Its target is not read now, + # so it belongs to neither allele and stays where it is. + locus = locus_at(76, alt_base="T") + self.assertLess(mp.tag_mismatches(ONE_BASE_DELETION, locus.alt_tag), mp.tag_mismatches(ONE_BASE_DELETION, locus.ref_tag)) + counts = {locus.ref_tag: 10**6, locus.alt_tag: 10**6, ONE_BASE_DELETION: 3} + distance = mp.tag_mismatches(ONE_BASE_DELETION, locus.alt_tag) + self.assertEqual(distance, 8) + self.assertEqual(mp._pooled_moves(locus, counts, (), distance, 2.0, BAND), {}) + # With gapped readings off the same row is an Alt-allele row and is folded. + self.assertEqual(mp._pooled_moves(locus, counts, (), distance, 2.0, 0), {ONE_BASE_DELETION: locus.alt_tag}) + + def test_pooled_denoiser_classifies_with_read_continuation(self): + # Target at the last base; Ref+late-deletion (common, protected) and Alt+late-deletion + # (rare, fails evidence) are both Other on the tag alone, but settle to RefMatch and + # AltMatch under read continuation and must never be folded together. + after = "CATTGACCTGAAGTCCATCGGTAAGCTTGA" + locus = locus_at(80, alt_base="C") + ref_del = (REF + after)[:78] + (REF + after)[79:] + alt_del = (locus.alt_tag + after)[:78] + (locus.alt_tag + after)[79:] + parent, parent_more = ref_del[:81], ref_del[81:109] + child, child_more = alt_del[:81], alt_del[81:109] + k_ref = {(0, locus.ref_tag): [(after[:28], 50)], (0, locus.alt_tag): [(after[:28], 50)]} + results = [ + mp.SampleResult(mp.Sample("s1", "s1", "u", {}), {(0, locus.ref_tag): 100, (0, parent): 100}, {}, {}, {}, {}, continuations={**k_ref, (0, parent): [(parent_more, 100)]}), + mp.SampleResult(mp.Sample("s2", "s2", "u", {}), {(0, locus.ref_tag): 100, (0, parent): 100}, {}, {}, {}, {}, continuations={**k_ref, (0, parent): [(parent_more, 100)]}), + mp.SampleResult(mp.Sample("s3", "s3", "u", {}), {(0, locus.alt_tag): 12, (0, child): 9}, {}, {}, {}, {}, continuations={**k_ref, (0, child): [(child_more, 9)]}), + ] + rule = mp.EvidenceRule(1, 20, 0, 10, 2, 30, 0.0) + with contextlib.redirect_stderr(io.StringIO()): + final = mp.finalize_counts(results, [locus], mp.DenoiseSettings(1, 1, 2.0), rule, BAND, jobs=1) + self.assertEqual(final[2].counts.get((0, parent), 0), 0) + self.assertEqual(final[2].counts[(0, child)], 9) + + def test_the_cells_this_table_states_are_what_generate_writes(self): + locus = locus_at(76, alt_base="T") + site_row = REF[:78] + "A" + REF[79:] + rows = [ + ("Ref", REF, "."), + ("Alt", locus.alt_tag, "77:G>T"), + ("RefMatch", site_row, "79:G>A"), + ("Other", ONE_BASE_DELETION, "unresolved=10"), + ] + for category, sequence, text in rows: + self.assertEqual(cell(locus, sequence), text) + if category not in ("Ref", "Alt"): + self.assertEqual(mp.classify_sequence(locus, sequence, BAND), category) + + def test_fixed_offset_reading_would_have_invented_sites(self): + events = mp._describe(REF, ONE_BASE_DELETION, BAND, gapped=False) + self.assertEqual(mp.format_variants(events), "72:A>G;73:G>T;74:T>A;76:A>G;77:G>T;78:T>G;79:G>T;80:T>G;81:G>C") + self.assertEqual(cell(locus_at(76, alt_base="T"), ONE_BASE_DELETION, 0), mp.format_variants(events)) + + +if __name__ == "__main__": + unittest.main()