diff --git a/.cargo/mutants.toml b/.cargo/mutants.toml new file mode 100644 index 0000000..27fdab7 --- /dev/null +++ b/.cargo/mutants.toml @@ -0,0 +1,36 @@ +# Mutation testing configuration. +# +# `cargo mutants` changes the source (flips a comparison, replaces a function +# body with a default) and reports whether the test suite notices. A surviving +# mutant is a piece of logic no test distinguishes: either a test is missing, or +# the logic does not do anything, and both are worth knowing. +# +# It is advisory. A surviving mutant is a question, not a defect, and it never +# fails CI. + +# The scientific core plus the readers that feed it. A flipped comparison in an +# estimator changes the distance someone publishes, and a flipped one in a +# reader changes which variants reach the estimator at all, which is the same +# thing one step earlier. +# +# The whole of src/ is examined rather than a subset. At 355 mutants that is +# affordable here, and drawing a boundary would mean maintaining it. +examine_globs = [ + "src/**/*.rs", +] + +# The test module itself carries no logic under test. +exclude_globs = [ + "src/calculation/tests.rs", +] + +# The whole suite, unit and integration alike. Integration tests drive the real +# binary through CARGO_BIN_EXE_fstic, which is what covers argument parsing, +# exit codes and the warnings, and none of that is reachable from --lib. It +# costs a rebuild per mutant and is worth it: the orchestration in main.rs is +# reachable no other way. +# +# The suite finishes in about a second, so anything still running after a minute +# is a mutant that made the code loop rather than one under test. +timeout_multiplier = 5.0 +minimum_test_timeout = 60 diff --git a/.github/CODE_OF_CONDUCT.md b/.github/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..04b3659 --- /dev/null +++ b/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +paula.ruiz.rodriguez@csic.es. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..ced29b1 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,65 @@ +# Contributing + +The full guide lives with the rest of the documentation, at +[pathogenomics-lab.github.io/fstic/about/contributing](https://pathogenomics-lab.github.io/fstic/about/contributing/). +This file is the short version, and the parts specific to working in the +repository itself. + +## Reporting a bug + +Use the [bug report form](https://github.com/PathoGenOmics-Lab/fstic/issues/new?template=bug_report.yml). +The two things that make a report actionable are the exact command and the +stderr output: Fstic counts everything it drops and prints it before the +summary, so that block usually says what happened. + +A wrong number is worth reporting even without a reproducer. Say what you +expected and why: the estimators have variants that differ in ways easy to +mistake for a bug in either direction. + +## Before opening a pull request + +```bash +cargo test +cargo clippy --all-targets +cargo fmt --check +``` + +CI runs those, plus a build on the minimum supported Rust version and a check +that the output does not change with the thread count. + +## Things worth knowing + +**A test that cannot fail is not a test.** Several here once asserted that the +output contained `0.000000`, which the hard-coded zero diagonal satisfies on any +matrix at all. If you add a test with a behaviour change, break the change on +purpose once and check the test notices. + +**Identity and fixed-difference cases rarely distinguish two estimators.** Both +send identical samples to 0 and complete differences to 1 or infinity. The case +that tells them apart is an intermediate frequency, which is where the Reynolds +defect hid for a release. + +**Use the shared helpers.** `get_all_freqs_at_pos` is where the "an absent +record means reference" rule lives, and `sum_per_locus` is what keeps a +reduction from depending on the thread count. A plain `par_iter().sum()` will +pass the unit tests and fail the determinism job. + +**Behaviour changes move with their documentation.** The pages under `docs/` +and the entry in `CHANGELOG.md` are part of the change, not follow-up work. CI +builds the site with `--strict`, so a link to a heading you renamed fails there. + +## Mutation testing + +Advisory, and run by hand: + +```bash +cargo mutants +``` + +It reports logic no test distinguishes. Configuration is in +`.cargo/mutants.toml`, and the same run is available as a workflow under +Actions. + +## Licence + +GPL-3.0. Contributions are accepted under the same terms. diff --git a/.github/DISCUSSION_TEMPLATE/q-a.yml b/.github/DISCUSSION_TEMPLATE/q-a.yml new file mode 100644 index 0000000..fbd4c69 --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/q-a.yml @@ -0,0 +1,35 @@ +labels: ["question"] +body: + - type: markdown + attributes: + value: | + Before asking, the two pages that answer most questions are + [choosing an estimator](https://pathogenomics-lab.github.io/fstic/guide/metrics/) + and [the model](https://pathogenomics-lab.github.io/fstic/how-it-works/model/). + The second one covers what an absent record means and why a pairwise + distance does not move when another sample joins the run. + + - type: textarea + id: question + attributes: + label: What would you like to know? + validations: + required: true + + - type: textarea + id: context + attributes: + label: Your data and command + description: > + The kind of data (consensus calls, within-host frequencies, pooled), + roughly how many samples and sites, and the command you ran. The stderr + block is useful here too: the warning counts often answer the question + on their own. + render: shell + + - type: dropdown + id: formula + attributes: + label: Which estimator are you using? + multiple: true + options: [fst, gst, nei, chord, bray-curtis, jost_d, reynolds, rogers, "not sure yet"] diff --git a/.github/DISCUSSION_TEMPLATE/studies-using-fstic.yml b/.github/DISCUSSION_TEMPLATE/studies-using-fstic.yml new file mode 100644 index 0000000..324938e --- /dev/null +++ b/.github/DISCUSSION_TEMPLATE/studies-using-fstic.yml @@ -0,0 +1,40 @@ +labels: ["studies"] +body: + - type: markdown + attributes: + value: | + If Fstic was part of an analysis you published or presented, we would + like to hear about it. Seeing which estimators people actually reach for, + and on what kind of data, is what tells us where the tool needs work. + + - type: input + id: study + attributes: + label: The study + description: Title, and a DOI or link if there is one. + validations: + required: true + + - type: textarea + id: use + attributes: + label: What did you use it for? + description: The organism, the kind of data, and what the distances fed into. + validations: + required: true + + - type: dropdown + id: formula + attributes: + label: Which estimator + multiple: true + options: [fst, gst, nei, chord, bray-curtis, jost_d, reynolds, rogers] + + - type: textarea + id: friction + attributes: + label: Anything that got in the way? + description: > + A step you had to script around, an output you had to reshape, a + default that was wrong for your data. This is the most useful box on + the form. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..0e7e92a --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,87 @@ +name: Bug report +description: A wrong number, a crash, or something that does not do what the docs say +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + Thanks for reporting. The two things that make a report actionable are + the exact command and the stderr output: Fstic counts everything it + drops and prints it before the summary, so that block usually says what + happened. + + For a wrong number, say what you expected and why. Several of the + estimators have variants that differ in ways easy to mistake for a bug + in either direction, so the reasoning matters as much as the value. + + - type: input + id: version + attributes: + label: Version + description: Output of `fstic --version` + placeholder: fstic 1.0.1 + validations: + required: true + + - type: dropdown + id: install + attributes: + label: How did you install it? + options: + - Bioconda + - Built from source with cargo + - Other + validations: + required: true + + - type: textarea + id: command + attributes: + label: The command you ran + render: shell + placeholder: fstic --vcf sample*.vcf --output d.csv --formula gst --min-depth 50 + validations: + required: true + + - type: textarea + id: stderr + attributes: + label: What it printed + description: > + The whole stderr block, including the filter echo at the top, any + warnings, and the summary. Capture it with `2> run.log` if it is long. + render: text + validations: + required: true + + - type: textarea + id: expected + attributes: + label: What you expected instead + description: For a wrong number, the value you expected and where it comes from. + validations: + required: true + + - type: textarea + id: input + attributes: + label: Input + description: > + A couple of small VCFs or a few table rows that show the problem, if you + can share them. A synthetic file that reproduces it is worth more than a + description of a real one you cannot attach. Please do not paste + identifiable sample data. + render: text + + - type: dropdown + id: formula + attributes: + label: Which estimator + multiple: true + options: [fst, gst, nei, chord, bray-curtis, jost_d, reynolds, rogers, "not estimator-specific"] + + - type: input + id: platform + attributes: + label: Platform + placeholder: Ubuntu 24.04 / macOS 15 arm64 / Windows 11 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..ea89d8c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,15 @@ +blank_issues_enabled: false +contact_links: + - name: Question about using Fstic + url: https://github.com/PathoGenOmics-Lab/fstic/discussions/new?category=q-a + about: > + How to choose an estimator, how to read a matrix, what a warning means. + Discussions rather than issues, so the answers stay findable. + - name: Documentation + url: https://pathogenomics-lab.github.io/fstic/ + about: > + The tutorial, the estimator guide, the filter reference and the model the + estimators rest on. + - name: A study that used Fstic + url: https://github.com/PathoGenOmics-Lab/fstic/discussions/new?category=studies-using-fstic + about: Tell us about it, so others can see how it is being used. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..6d20f2f --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,41 @@ +name: Feature request +description: Something Fstic should do and does not +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + Describe the analysis you are trying to do rather than the flag you + think you need. The flag is usually the easier half to get right once + the problem is clear. + + - type: textarea + id: problem + attributes: + label: What are you trying to do? + description: The analysis, and where Fstic stops being able to help. + validations: + required: true + + - type: textarea + id: workaround + attributes: + label: What do you do instead today? + description: > + Another tool, a preprocessing step, a script. Useful even when the + answer is "nothing, I gave up": it says how much the gap costs. + + - type: textarea + id: proposal + attributes: + label: What would it look like? + description: A flag, an output column, a new estimator. A sketch is fine. + + - type: textarea + id: reference + attributes: + label: Reference + description: > + For a new estimator, the paper defining it. Fstic implements published + estimators under their published names, so a citation is what makes one + implementable and checkable. diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..50eb964 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,30 @@ +# Security + +Fstic is a command-line tool that reads local files and writes a matrix. It +opens no network connections and runs no code from its input. The realistic +concerns are a malformed input file causing a crash or unbounded memory use, +and a vulnerability in a dependency. + +## Reporting + +Please report anything security-relevant privately, through +[GitHub's advisory form](https://github.com/PathoGenOmics-Lab/fstic/security/advisories/new), +rather than as a public issue. + +Include the input that triggers it, or a description sufficient to construct +one. Expect an initial reply within a week. + +## Supported versions + +The latest release. Fixes go into a new release rather than being backported. + +## What is already covered + +Pull requests are checked by CodeQL, and by a dependency review that refuses a +new dependency carrying a known advisory. `cargo audit` runs on every pull +request against the whole tree, advisory rather than blocking. Dependabot opens +security updates as soon as an advisory lands, independently of the monthly +grouped updates. + +A crash on malformed input is a bug worth reporting, but it is an ordinary +issue rather than an advisory unless you can show it does more than crash. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..cb3343f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,81 @@ +# Dependency updates. +# +# Grouped and monthly rather than one pull request per dependency as they land. +# The shape matters more than the frequency: a routine bump that survives the +# suite has been examined more carefully than anyone would examine it by eye, +# while a major changes APIs and wants a person. Keeping those apart is what +# lets the first kind merge itself without the second riding along. +# +# The minor and patch groups merge automatically once CI passes; see +# .github/workflows/dependabot-auto-merge.yml. The major groups never do. +# +# `schedule` here is Dependabot's own timer, not a cron in GitHub Actions. The +# only workflow in this repository that runs on a schedule is the issue sweep. +# +# Security updates are a separate mechanism, enabled in the repository settings +# and unaffected by any of this: a vulnerable dependency still gets its own pull +# request the day the advisory lands, major or not. + +version: 2 + +updates: + # The crate itself. + - package-ecosystem: cargo + directory: "/" + schedule: + interval: monthly + open-pull-requests-limit: 3 + labels: ["dependencies", "rust"] + commit-message: + prefix: "cargo" + groups: + cargo-routine: + patterns: ["*"] + update-types: ["minor", "patch"] + cargo-major: + patterns: ["*"] + update-types: ["major"] + + # The documentation site's build dependencies. They live in docs/ rather than + # at the root so that Dependabot finds them next to what they build. + - package-ecosystem: pip + directory: "/docs" + schedule: + interval: monthly + open-pull-requests-limit: 2 + labels: ["dependencies", "documentation"] + commit-message: + prefix: "docs" + groups: + docs-routine: + patterns: ["*"] + update-types: ["minor", "patch"] + docs-major: + patterns: ["*"] + update-types: ["major"] + + # The actions the workflows pin. These go stale silently: a deprecated runner + # image or a Node version dropped from an action is only noticed when a job + # starts warning, or fails. + # + # One exception is configured below rather than left to be discovered. The + # minimum supported Rust version is checked by passing `toolchain:` as an + # input to dtolnay/rust-toolchain, not by pinning the action to + # `rust-toolchain@1.82`. Written the second way, Dependabot reads the version + # as an action ref and helpfully bumps it, and the job then goes on passing + # while verifying a compiler that is no longer the floor. + - package-ecosystem: github-actions + directory: "/" + schedule: + interval: monthly + open-pull-requests-limit: 2 + labels: ["dependencies", "github-actions"] + commit-message: + prefix: "actions" + groups: + actions-routine: + patterns: ["*"] + update-types: ["minor", "patch"] + actions-major: + patterns: ["*"] + update-types: ["major"] diff --git a/.github/labeler.yml b/.github/labeler.yml new file mode 100644 index 0000000..ba28eaf --- /dev/null +++ b/.github/labeler.yml @@ -0,0 +1,58 @@ +# Which part of the project a pull request touches, worked out from the files it +# changes. The labels exist so that "what changed in the estimators" is a +# question the pull request list can answer; applying them by hand is how they +# stop being applied. +# +# The issue forms label their own issues, so this only has to cover pull +# requests. +# +# Format is actions/labeler v5, which is not v4's: a bare list of globs under +# the label name silently matches nothing. + +estimators: + - changed-files: + - any-glob-to-any-file: + - "src/calculation/**" + - "src/calculation.rs" + +io: + - changed-files: + - any-glob-to-any-file: + - "src/io/**" + - "src/io.rs" + +cli: + - changed-files: + - any-glob-to-any-file: + - "src/cli.rs" + - "src/main.rs" + +documentation: + - changed-files: + - any-glob-to-any-file: + - "docs/**" + - "mkdocs.yml" + - "README.md" + - "CHANGELOG.md" + +tests: + - changed-files: + - any-glob-to-any-file: + - "tests/**" + - "src/calculation/tests.rs" + +packaging: + - changed-files: + - any-glob-to-any-file: + - "Cargo.toml" + - "Cargo.lock" + - ".github/workflows/release.yml" + +# Everything under .github, not a list of the files there. Naming them one by +# one would leave `.github/labeler.yml` itself uncovered, so the pull request +# adding a rule to this file would arrive with no label, which is a small thing +# that says exactly how the list would age. +ci: + - changed-files: + - any-glob-to-any-file: + - ".github/**" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..d3f9545 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,35 @@ +## What this changes + + + +## Why + + + +## Does it change any numbers? + + + +- [ ] Output is unchanged for existing inputs +- [ ] Output changes, and the changes are described above and in `CHANGELOG.md` + +## Checks + +- [ ] `cargo test` passes +- [ ] `cargo clippy --all-targets` adds no warnings +- [ ] `cargo fmt --check` is clean +- [ ] Behaviour changes are covered by a test that fails without the change +- [ ] Documentation under `docs/` moved with the code, if behaviour changed + + diff --git a/.github/scripts/check_determinism.sh b/.github/scripts/check_determinism.sh new file mode 100755 index 0000000..fa951ca --- /dev/null +++ b/.github/scripts/check_determinism.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Run every estimator at several thread counts and require byte-identical +# output. A difference here means a reduction is being combined in an order that +# depends on how rayon happened to split the work, which makes the result a +# function of the machine it ran on. +set -euo pipefail + +BIN=./target/release/fstic +WORKERS=(1 2 3 5 8) +COMMON=(--vcf det_a.vcf det_b.vcf --min-depth 1 --min-af 0.01 + --min-alt-reads 1 --min-alt-rev-reads 0) + +status=0 +for formula in fst gst nei chord bray-curtis jost_d reynolds rogers; do + reference="" + for w in "${WORKERS[@]}"; do + out="det_${formula}_w${w}.csv" + "$BIN" "${COMMON[@]}" --formula "$formula" --workers "$w" --output "$out" 2>/dev/null + if [[ -z "$reference" ]]; then + reference="$out" + continue + fi + if ! cmp -s "$reference" "$out"; then + echo "FAIL ${formula}: --workers ${w} differs from the single-threaded run" + diff <(cat "$reference") <(cat "$out") || true + status=1 + fi + done + [[ $status -eq 0 ]] && echo "ok ${formula}" +done + +if [[ $status -ne 0 ]]; then + echo + echo "Output depends on the thread count. The per-locus reductions in" + echo "src/calculation/common.rs are meant to run over fixed-size chunks" + echo "combined in index order; a plain par_iter().sum() reintroduces this." +fi +exit $status diff --git a/.github/scripts/make_determinism_input.py b/.github/scripts/make_determinism_input.py new file mode 100755 index 0000000..2bd0107 --- /dev/null +++ b/.github/scripts/make_determinism_input.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +"""Write two VCFs large enough that the summation order shows in the output. + +Floating point addition is not associative, so a reduction whose tree depends on +the thread count differs in the last digits. Making that visible needs care in +two directions, both of which were established by breaking the reduction on +purpose and checking that this input catches it: + + * Size. On a handful of loci the difference sits below the printed precision + and nothing is observable. The effect this guards against was found at a few + hundred thousand loci, so that is the scale used here. + + * Irregularity. An earlier version of this generator walked the frequencies + with a fixed arithmetic stride, and the deliberately broken build passed: + values that regular produce partial sums that agree whatever order they are + added in. Drawing them at random is what exposes it. + +Seeded, so "random" here means irregular rather than different every run. A +failure reproduces exactly, which is the whole point of a regression check. +""" + +import pathlib +import random + +POSITIONS = 400_000 +DENSITY = 0.85 +SEED = 20260728 + +HEADER = ( + "##fileformat=VCFv4.2\n" + "##contig=\n" + "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample\n" +) + + +def write(name: str, rng: random.Random) -> None: + rows = [HEADER] + for pos in range(1, POSITIONS + 1): + if rng.random() >= DENSITY: + continue + freq = rng.uniform(2.0, 98.0) + rows.append( + f"chr1\t{pos}\t.\tA\tT\t.\tPASS\t.\tGT:DP:FREQ\t0/1:100:{freq:.6f}%\n" + ) + pathlib.Path(name).write_text("".join(rows)) + print(f"wrote {name} ({len(rows) - 1} variants)") + + +rng = random.Random(SEED) +write("det_a.vcf", rng) +write("det_b.vcf", rng) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..3991a17 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,120 @@ +name: CI + +# Quality gate for fstic. Runs once on a pull request, and again on main after +# the merge. +# +# `push` is restricted to main rather than firing on every branch. With both +# triggers open, a commit on a branch with a pull request open runs the whole +# suite twice against the same commit: two notifications for one result. This +# way each commit is checked exactly once, and main itself is still checked +# after a merge. +# +# The cost is that a branch pushed without a pull request is not checked. +# Nothing reaches main that way, since main takes pull requests and the checks +# it requires are reported by the `pull_request` run. + +on: + push: + branches: [main] + pull_request: + +# A second push to a pull request makes the first run's answer irrelevant, so +# stop it rather than pay for it. Runs on main are left alone: those record +# whether a merged commit is sound, and a cancelled one records nothing. +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +# Every job here reads the repository, builds it and runs tests. None writes a +# comment, a label, a release or a commit. Without this block they would run +# with whatever the repository default grants, which is more than that and +# grows silently if the default is ever widened. +permissions: + contents: read + +# Each job carries a `timeout-minutes`, because the default is six hours. What +# matters is not how long a job takes but how long a stuck one takes to say so. +env: + CARGO_TERM_COLOR: always + +jobs: + rust: + name: Build · test · clippy · fmt + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: rustfmt, clippy + - uses: Swatinem/rust-cache@v2 + - name: Format check + run: cargo fmt --check + - name: Clippy (deny warnings) + run: cargo clippy --all-targets -- -D warnings + - name: Build + run: cargo build --locked + - name: Test + run: cargo test --locked + # Packaging breaks in ways nothing else here notices: a file the build + # needs left out of `include`, metadata crates.io refuses, a size over the + # limit. Every one of those fails at release time, after the tag is + # pushed, which is the expensive moment to find out. + - name: The crate still packages and builds from its own tarball + run: cargo publish --dry-run --locked + + msrv: + name: Builds on the minimum supported Rust version + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + # The version is an input, deliberately, and not `rust-toolchain@1.85`. + # Written as an action ref, Dependabot reads it as a version to keep + # current and bumps it, and this job then goes on passing while verifying + # a compiler that is no longer the floor. As an input it is invisible to + # Dependabot and changes only when someone changes it. + # + # Keep it equal to `rust-version` in Cargo.toml. cargo enforces that field + # against the toolchain, so a mismatch fails here rather than drifting. + - uses: dtolnay/rust-toolchain@master + with: + toolchain: "1.85" + - uses: Swatinem/rust-cache@v2 + - name: Build and test on the floor + run: cargo test --locked + + # The estimators are the reason anyone runs this, and two of their properties + # are not visible in a single run: that a pairwise distance does not depend on + # which other samples are in the cohort, and that the answer does not depend + # on the thread count. Both are covered by the integration suite above, but + # only at the sizes a unit test can afford. This runs the release binary over + # a larger input at several thread counts and diffs the output, which is where + # a reduction-order regression would actually show. + determinism: + name: Output does not depend on the worker count + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Build + run: cargo build --release --locked + - name: Generate a dataset large enough for the summation order to matter + run: python3 .github/scripts/make_determinism_input.py + - name: Every estimator agrees across thread counts + run: bash .github/scripts/check_determinism.sh + + audit: + name: cargo audit (advisory, non-blocking) + runs-on: ubuntu-latest + timeout-minutes: 20 + continue-on-error: true + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Install cargo-audit + run: cargo install cargo-audit --locked + - name: Audit dependencies + run: cargo audit diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..75cf132 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,71 @@ +name: CodeQL + +# Static analysis over everything this repository is written in. clippy checks +# the shape of a line and the test suite checks the answer, while these queries +# follow a value across functions and files and ask where an unchecked one +# arrives somewhere it matters. +# +# Three languages, which is all of them: +# +# rust the tool itself +# python the CI helper scripts under .github/scripts +# actions the workflows themselves, including this one +# +# That last one is not a curiosity. These queries know about unsafe uses of +# `pull_request_target`, which is the trigger `labeler.yml` runs on, and about +# script injection through untrusted context values. Reasoning that a workflow +# is safe is exactly the kind of reasoning worth having checked by something +# that is not the person who wrote it. +# +# On pushes to main and on pull requests, with no schedule. GitHub's own default +# setup adds a weekly run; this does not, in keeping with every other workflow +# here except the issue sweep, which has nothing but time to hang off. +# +# `build-mode: none` reads the source without compiling it. It is what makes this +# take a minute rather than a full release build, and it is the documented mode +# for interpreted languages and for the compiled ones that support it. + +on: + push: + branches: [main] + pull_request: + +# A newer push makes an older analysis irrelevant, the same as CI. +concurrency: + group: codeql-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + security-events: write + contents: read + actions: read + +jobs: + analyze: + name: Analyse ${{ matrix.language }} + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - language: rust + build-mode: none + - language: python + build-mode: none + - language: actions + build-mode: none + + steps: + - uses: actions/checkout@v4 + + - name: Initialise CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + + - name: Analyse + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{ matrix.language }}" diff --git a/.github/workflows/dependabot-auto-merge.yml b/.github/workflows/dependabot-auto-merge.yml new file mode 100644 index 0000000..b565f08 --- /dev/null +++ b/.github/workflows/dependabot-auto-merge.yml @@ -0,0 +1,90 @@ +name: Dependabot auto-merge + +# Merges Dependabot's routine updates once CI has passed, and never touches a +# major one. +# +# The point of the split is that a minor or patch bump that survives the whole +# suite (83 tests, the MSRV build, the thread-count determinism check and the +# strict documentation build) has already been examined more carefully than a +# person would examine it by eye, while a major bump changes APIs and wants a +# person to look. +# +# Triggered by the pull request itself, not by a schedule. + +on: pull_request + +permissions: + contents: write + pull-requests: write + +jobs: + auto-merge: + name: Merge routine updates once CI is green + runs-on: ubuntu-latest + timeout-minutes: 10 + if: github.event.pull_request.user.login == 'dependabot[bot]' + steps: + - name: Read what this pull request updates + id: metadata + uses: dependabot/fetch-metadata@v3 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + + # The rule, decided once. + # + # It used to be written twice, once negated for the step that explains + # itself, and the two halves drifted the moment the first was edited: a + # grouped patch matched the merge step and the "left alone" step at the + # same time, so it would have merged and announced that it had not. One + # step decides, the other two read the answer. + # + # Named rather than excluded: merge when the pull request says in so many + # words that it is a patch or a minor, or when it is a `-routine` group, + # which the configuration already restricts to those two. + # + # Asking instead whether the update was "not major" let one through. A pip + # requirement bump, `pillow ~=11.0` to `~=12.3`, reports no update type at + # all, and an empty string is not equal to major, so the rule said yes to + # a major on its first day. Anything this cannot positively identify still + # waits for a person. + # + # The update-type test once applied only to ungrouped pull requests, + # because it was unclear what a grouped one reports. It reports "the + # highest semver change being made by this PR", so a group carrying one + # major is a major here. That is what lets the coupled npm families in + # dependabot.yml hold patches and majors alike without a major slipping + # through on the back of a patch. + - name: Decide whether this one may merge itself + id: decide + env: + GROUP: ${{ steps.metadata.outputs.dependency-group }} + UPDATE_TYPE: ${{ steps.metadata.outputs.update-type }} + run: | + set -euo pipefail + may_merge=false + case "$GROUP" in + *-routine) may_merge=true ;; + esac + case "$UPDATE_TYPE" in + version-update:semver-patch|version-update:semver-minor) may_merge=true ;; + esac + # Printed because a decision nobody can read is a decision nobody can + # correct: this line is what a later surprise gets diagnosed from. + echo "group='${GROUP}' update-type='${UPDATE_TYPE}' -> may-merge=${may_merge}" + echo "may-merge=${may_merge}" >> "$GITHUB_OUTPUT" + + - name: Queue the merge + if: steps.decide.outputs.may-merge == 'true' + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Say why this one was left alone + if: steps.decide.outputs.may-merge != 'true' + run: | + gh pr comment "$PR_URL" --body \ + "Left for review. Only a \`-routine\` group, or an update that identifies itself as patch or minor, merges on its own once CI passes. This one is a major update or does not say which it is." + env: + PR_URL: ${{ github.event.pull_request.html_url }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 0000000..c1e703d --- /dev/null +++ b/.github/workflows/dependency-review.yml @@ -0,0 +1,37 @@ +name: Dependency review + +# Stops a pull request that would bring in a dependency with a known +# vulnerability, which is the half of the problem Dependabot does not cover. +# Dependabot tells you about a vulnerable dependency you already have; this +# refuses the one you are about to add, while refusing it is still free. +# +# It compares the dependency graph of the base against the head, so it only ever +# has an opinion about what the pull request itself introduces. Everything +# already in the tree is somebody else's conversation, and is `cargo audit`'s +# job in CI. +# +# `moderate` rather than the default `low`: a low severity advisory on a +# transitive build dependency is worth reading and is not worth blocking a merge +# on, and a gate that blocks for things nobody acts on stops being read. + +on: + pull_request + +permissions: + contents: read + # For the summary comment it leaves when it refuses one. + pull-requests: write + +jobs: + review: + name: No new dependency with a known vulnerability + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + - uses: actions/dependency-review-action@v4 + with: + fail-on-severity: moderate + # Only when it has something to say. A summary on every pull request + # is a summary nobody reads by the third one. + comment-summary-in-pr: on-failure diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index f01d774..1e9cddc 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -17,14 +17,14 @@ on: - "docs/**" - "mkdocs.yml" - "CHANGELOG.md" - - "requirements-docs.txt" + - "docs/requirements.txt" - ".github/workflows/docs.yml" pull_request: paths: - "docs/**" - "mkdocs.yml" - "CHANGELOG.md" - - "requirements-docs.txt" + - "docs/requirements.txt" - ".github/workflows/docs.yml" workflow_dispatch: @@ -47,7 +47,7 @@ jobs: python-version: "3.x" - name: Install dependencies - run: pip install -r requirements-docs.txt + run: pip install -r docs/requirements.txt # --strict turns broken internal links and missing nav entries into # errors, so a pull request that breaks one fails here instead of @@ -78,7 +78,7 @@ jobs: mkdocs-material- - name: Install dependencies - run: pip install -r requirements-docs.txt + run: pip install -r docs/requirements.txt - name: Build and deploy run: mkdocs gh-deploy --force --strict diff --git a/.github/workflows/labeler.yml b/.github/workflows/labeler.yml new file mode 100644 index 0000000..cdd64cb --- /dev/null +++ b/.github/workflows/labeler.yml @@ -0,0 +1,34 @@ +name: Label pull requests + +# Puts the part-of-the-project labels on a pull request from the files it +# changes, so the labels are actually there when someone wants to filter by them. +# Configuration lives in .github/labeler.yml. +# +# `pull_request_target` rather than `pull_request` because a pull request from a +# fork gets a read-only token on `pull_request`, and labelling needs write. It +# runs the workflow from the base branch and never checks out or executes the +# pull request's code, which is what makes that safe here: this job reads the +# list of changed filenames and writes labels, and touches nothing from the +# branch it is labelling. + +on: + pull_request_target: + types: [opened, synchronize, reopened] + +permissions: + contents: read + pull-requests: write + +jobs: + label: + name: Apply labels from the files changed + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/labeler@v5 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + # Off on purpose. With it on, the action removes any configured label + # the files no longer justify, including one a person put there + # deliberately. + sync-labels: false diff --git a/.github/workflows/mutants.yml b/.github/workflows/mutants.yml new file mode 100644 index 0000000..2e727da --- /dev/null +++ b/.github/workflows/mutants.yml @@ -0,0 +1,100 @@ +name: Mutation testing (advisory) + +# `cargo mutants` changes the source and reports whether the test suite notices. +# A surviving mutant is a piece of logic no test distinguishes: either a test is +# missing, or the logic does nothing, and both are worth knowing. +# +# Run by hand rather than on every push, because it builds and tests once per +# mutant. It never fails the build: a surviving mutant is a question to look at, +# not a defect. +# +# Scope, test selection and timeouts live in `.cargo/mutants.toml`, so a local +# run matches this one. +# +# Split across four shards. The configured scope generates 355 mutants, and a +# measured shard of 45 took 1m35s on a warm laptop, so the whole run is roughly +# a quarter of an hour there and rather more on a runner. Four shards keep each +# job comfortably inside its limit and let a failure be re-run cheaply. + +on: + workflow_dispatch: + +# It reads the repository, mutates a copy of the source in a scratch directory +# and uploads a report as an artifact. It writes nothing back here. +permissions: + contents: read + +env: + CARGO_TERM_COLOR: always + +jobs: + mutants: + name: Shard ${{ matrix.shard }} of 0 to 3 + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + # Zero-indexed, which the flag's own help does not say: it gives `1/4` + # as the example. Numbering these 1 to 4 would quietly skip shard 0 and + # run an empty shard 4, covering three quarters of the mutants while + # reporting a full set of results. + shard: [0, 1, 2, 3] + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: Swatinem/rust-cache@v2 + - name: Install cargo-mutants + run: cargo install cargo-mutants --locked + - name: Run shard ${{ matrix.shard }} + # Never fails the job: the report is the output, not the exit code. + run: cargo mutants --shard ${{ matrix.shard }}/4 --no-shuffle || true + - name: Upload the report + if: always() + uses: actions/upload-artifact@v4 + with: + name: mutants-shard-${{ matrix.shard }} + path: mutants.out/ + if-no-files-found: warn + + summary: + name: Put the shards back together + needs: mutants + if: always() + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/download-artifact@v4 + with: + pattern: mutants-shard-* + path: shards + # One list to read, rather than four artifacts to download and diff by + # hand. Written to the job summary so it is visible without downloading + # anything at all. + - name: Collect the survivors + run: | + set -euo pipefail + missed=$(cat shards/*/missed.txt 2>/dev/null | sort -u || true) + timeouts=$(cat shards/*/timeout.txt 2>/dev/null | sort -u || true) + { + echo "## Surviving mutants" + echo + if [ -z "$missed" ]; then + echo "None. Every mutant in scope was caught by the suite." + else + echo "Each line is a change to the source that no test noticed." + echo + echo '```' + echo "$missed" + echo '```' + fi + if [ -n "$timeouts" ]; then + echo + echo "## Timed out" + echo + echo '```' + echo "$timeouts" + echo '```' + fi + } >> "$GITHUB_STEP_SUMMARY" + echo "$missed" | grep -c . | xargs echo "surviving mutants:" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..441e0bd --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,340 @@ +name: Build & Release + +# Cut a release by pushing a tag. Everything below hangs off that: the binaries, +# the checksums, the provenance, the crates.io publish and the notes. Nothing +# here needs a person to remember a step, which is the point: bioconda and +# Zenodo fall behind precisely because publishing is a thing someone does by +# hand afterwards. +# +# The release is created as a draft and published at the end, so a matrix that +# fails halfway leaves an unpublished draft rather than a release carrying +# binaries for two platforms out of four. + +permissions: + contents: write + +on: + push: + tags: + - "v*" + workflow_dispatch: + +env: + CARGO_TERM_COLOR: always + +jobs: + build: + name: Build ${{ matrix.asset_suffix }} + strategy: + fail-fast: false + matrix: + include: + - platform: macos-15 + rust_target: aarch64-apple-darwin + asset_suffix: macos-aarch64 + - platform: macos-15 + rust_target: x86_64-apple-darwin + asset_suffix: macos-x86_64 + - platform: ubuntu-22.04 + rust_target: x86_64-unknown-linux-gnu + asset_suffix: linux-x86_64 + - platform: windows-latest + rust_target: x86_64-pc-windows-msvc + asset_suffix: windows-x86_64 + + runs-on: ${{ matrix.platform }} + timeout-minutes: 30 + + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.rust_target }} + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.rust_target }} + + # ubuntu-22.04 rather than latest, deliberately. The binary links against + # the runner's glibc, and building on a newer image raises the minimum + # glibc every user needs without anything saying so. Cluster nodes are + # routinely older than the newest runner image. + - name: Build + run: cargo build --release --locked --target ${{ matrix.rust_target }} + + - name: Package (Unix) + if: runner.os != 'Windows' + shell: bash + run: | + set -euo pipefail + package_dir="dist/fstic_${{ github.ref_name }}_${{ matrix.asset_suffix }}" + mkdir -p "$package_dir" + cp "target/${{ matrix.rust_target }}/release/fstic" "$package_dir/fstic" + cp README.md CHANGELOG.md LICENSE "$package_dir/" + tar -C dist -czf "${package_dir}.tar.gz" "$(basename "$package_dir")" + + - name: Package (Windows) + if: runner.os == 'Windows' + shell: pwsh + run: | + $packageDir = "dist/fstic_${{ github.ref_name }}_${{ matrix.asset_suffix }}" + New-Item -ItemType Directory -Force -Path $packageDir | Out-Null + Copy-Item "target/${{ matrix.rust_target }}/release/fstic.exe" "$packageDir/fstic.exe" + Copy-Item README.md, CHANGELOG.md, LICENSE -Destination $packageDir + Compress-Archive -Path $packageDir -DestinationPath "$packageDir.zip" -Force + + # The binary is built here and run nowhere. A cross-compiled or + # mis-packaged archive would be found by whoever downloaded it. This + # unpacks what is about to be uploaded and runs it, on the runners where + # that is possible at all. + - name: The packaged binary runs and reports the tagged version + if: matrix.rust_target != 'x86_64-apple-darwin' + shell: bash + run: | + set -euo pipefail + cd dist + case "${{ runner.os }}" in + Windows) unzip -q "fstic_${{ github.ref_name }}_${{ matrix.asset_suffix }}.zip" -d check + binary="check/fstic_${{ github.ref_name }}_${{ matrix.asset_suffix }}/fstic.exe" ;; + *) tar -xzf "fstic_${{ github.ref_name }}_${{ matrix.asset_suffix }}.tar.gz" -C . + binary="fstic_${{ github.ref_name }}_${{ matrix.asset_suffix }}/fstic" ;; + esac + reported=$("$binary" --version) + echo "$reported" + expected="fstic ${GITHUB_REF_NAME#v}" + if [ "$reported" != "$expected" ]; then + echo "packaged binary says '$reported', tag says '$expected'" >&2 + exit 1 + fi + + - name: Upload to the draft release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ github.ref_name }} + name: "fstic ${{ github.ref_name }}" + draft: true + prerelease: ${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') || contains(github.ref_name, 'rc') }} + # No notes here. The finalize job writes them once, from the tag, and + # overwrites whatever created the draft put in. + files: | + dist/*.tar.gz + dist/*.zip + + # crates.io, from the tag, so it cannot fall behind. + # + # It waits for the whole matrix. If a platform failed, this is not a release, + # and a crates.io version is permanent: `cargo yank` hides it from resolution + # and nothing ever deletes it. That asymmetry is why this refuses more readily + # than the other jobs. + # + # Needs CARGO_REGISTRY_TOKEN in the repository secrets. Without one the job + # says so and stops, rather than failing with an authentication error that + # reads like a broken workflow. + crates: + name: Publish to crates.io + needs: build + if: startsWith(github.ref, 'refs/tags/') + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + + - name: Check there is a token to publish with + env: + TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: | + set -euo pipefail + if [ -z "${TOKEN}" ]; then + echo "No CARGO_REGISTRY_TOKEN is set, so this release is not going to crates.io." >&2 + echo "Add one under Settings -> Secrets and variables -> Actions to turn this on." >&2 + exit 1 + fi + + # The version in Cargo.toml and the tag are one fact written twice, and + # crates.io cannot be corrected afterwards: publishing 1.0.1 under a tag + # that says 1.0.2 is permanent. Compared here rather than trusted. + - name: The tag and Cargo.toml agree on the version + env: + TAG: ${{ github.ref_name }} + run: | + set -euo pipefail + manifest=$(cargo metadata --no-deps --format-version 1 \ + | python3 -c "import json,sys; print(json.load(sys.stdin)['packages'][0]['version'])") + if [ "${TAG#v}" != "$manifest" ]; then + echo "tag says ${TAG#v} and Cargo.toml says $manifest; refusing to publish" >&2 + exit 1 + fi + echo "both say $manifest" + + - name: Publish + env: + CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} + run: cargo publish --locked + + # Everything above uploads binaries and nothing says what they should contain. + # Someone who downloads an archive has no way to tell a good download from a + # truncated one, and no way to tell either from a substituted one. This + # publishes one SHA256SUMS covering every asset, in the format `sha256sum -c` + # reads, then signs a statement about where those bytes came from, then + # publishes the release. + # + # It waits on the whole matrix, so the file covers all four platforms or is + # not written at all: a checksums file that silently covered three out of four + # would be worse than none. + finalize: + name: Publish checksums, provenance and the release notes + needs: [build, crates] + if: startsWith(github.ref, 'refs/tags/') + runs-on: ubuntu-latest + timeout-minutes: 20 + + permissions: + contents: write + # Provenance is signed with the workflow's own short-lived identity, which + # is what makes the attestation say something a person could not forge by + # uploading a file. + id-token: write + attestations: write + + steps: + - uses: actions/checkout@v4 + + - name: Checksum every asset on the release + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ github.ref_name }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + mkdir -p release-assets + # The release is still a draft here. Draft assets are downloadable by + # an authenticated token, which is what makes this possible before the + # release is published. + gh release download "$TAG" --repo "$REPO" --dir release-assets --pattern '*' --clobber + + # On a rerun the previous SHA256SUMS is itself an asset, and would be + # checksummed into its own successor. + rm -f release-assets/SHA256SUMS + + count=$(find release-assets -maxdepth 1 -type f | wc -l) + if [ "$count" -eq 0 ]; then + echo "the release carries no assets: refusing to publish an empty checksums file" >&2 + exit 1 + fi + + # LC_ALL=C so the order does not depend on the runner's locale, and + # `--` so a name beginning with a dash stays a name. + (cd release-assets && LC_ALL=C sha256sum -- * > ../SHA256SUMS) + + # Read it back and check it against the bytes on disk, rather than + # trusting that writing it worked. + (cd release-assets && sha256sum -c ../SHA256SUMS) + + echo "checksummed $count assets" + cat SHA256SUMS + gh release upload "$TAG" SHA256SUMS --repo "$REPO" --clobber + + # The checksums say a download arrived intact. They cannot say where it + # came from: a checksums file and the file it describes can both be + # replaced by whoever can write to the release. This signs a statement, + # with the workflow's own short-lived identity rather than a stored key, + # that these exact bytes were built by this workflow from this commit. + - name: Attest that these binaries came from this commit + uses: actions/attest-build-provenance@v2 + with: + # The same set the checksums cover: the step above leaves them in + # release-assets/, with the previous SHA256SUMS already removed. + subject-path: "release-assets/*" + + # The notes say only what is true of any release and derive the rest from + # the tag, so there is nothing to keep in step by hand. A paragraph typed + # in here would outlive its release and describe every later one wrongly. + - name: Write the release notes and publish + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + TAG: ${{ github.ref_name }} + REPO: ${{ github.repository }} + run: | + set -euo pipefail + version="${TAG#v}" + + # Cutting a release with nothing written about it in the changelog is + # a mistake rather than a decision, and the notes below link to that + # entry. Fail here, where the draft is still unpublished and the entry + # can be added, rather than link a reader to a version the changelog + # never mentions. + if ! grep -q "^## \[${version}\]" CHANGELOG.md; then + echo "CHANGELOG.md has no '## [${version}]' entry: refusing to announce a release the changelog does not describe" >&2 + exit 1 + fi + + # Quoted heredoc: the body is written literally, backticks and all, + # and the placeholders are filled afterwards. An unquoted one would + # run the fenced commands instead of printing them. + cat > NOTES.template <<'MARKDOWN' + ## fstic @TAG@ + + Everything that changed in this version is listed in the + [changelog](https://github.com/@REPO@/blob/@TAG@/CHANGELOG.md), pinned to + this release. Full documentation lives at + , and the + [tutorial](https://pathogenomics-lab.github.io/fstic/tutorial/) runs four + samples from raw VCFs to a tree. + + ### Install + + ```bash + conda install -c bioconda fstic + ``` + + Or take an archive below: each holds the `fstic` binary for one + platform, with the README, the changelog and the licence. + + ### Check what you downloaded + + `SHA256SUMS` covers every asset in this release. Download it next to + the file you took and check the two together: + + ```bash + sha256sum --ignore-missing -c SHA256SUMS + ``` + + Each file it finds prints `OK`. On macOS, `shasum -a 256 + --ignore-missing -c SHA256SUMS` does the same. + + ### Check where it came from + + That tells you the download arrived intact. This tells you what it is: + + ```bash + gh attestation verify --repo @REPO@ + ``` + + Every binary here is signed with a statement that this workflow built + it from this repository, at the commit this release was cut from. It + needs no key of ours and no trust in this page. + MARKDOWN + + # YAML strips the block's own indentation, so the heredoc arrives at + # column zero. Plain `sed` into a second file rather than `sed -i`, + # whose spelling differs between GNU and BSD: this way the step can be + # run and checked on a laptop, not only on the runner. + sed "s|@TAG@|${TAG}|g; s|@REPO@|${REPO}|g" NOTES.template > NOTES.md + + if grep -q '@TAG@\|@REPO@' NOTES.md; then + echo "a placeholder survived into the notes" >&2 + exit 1 + fi + + echo "--- notes ---"; cat NOTES.md; echo "-------------" + + # Overwrites whatever created the draft put there, so there is one + # source for the notes and not two, and publishes it: everything that + # had to succeed has succeeded by this point. + gh release edit "$TAG" --repo "$REPO" \ + --notes-file NOTES.md \ + --draft=false diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..d46a38c --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,73 @@ +name: Close abandoned issues + +# Marks issues nobody has touched in three months, and closes them a month after +# that if still nothing. The point is not tidiness: an issue list where half the +# entries are questions someone stopped caring about is a list nobody reads, and +# then the real reports get missed too. +# +# This is the only scheduled workflow here, and it is deliberate. Everything else +# runs on a push, a pull request or by hand, because a workflow that fires on a +# timer is one nobody is watching when it goes wrong. A stale sweep has nothing +# to hang off except time, so it gets the exception rather than the rule getting +# dropped. +# +# It is set up so that being wrong is cheap: +# +# * Three months of silence, then another month before anything closes. A +# report from someone who is waiting on a reply is not abandoned. +# * Anything labelled `bug`, `security` or `pinned` is never touched. A +# confirmed defect does not stop existing because nobody commented on it. +# * Pull requests are left alone entirely. +# * A closed issue can be reopened by anyone with a comment, and the message +# says so. +# +# `workflow_dispatch` is here too, so the sweep can be run and watched on purpose +# rather than only meeting it after the fact. + +on: + schedule: + # Mondays at 06:00 UTC. Weekly is far more often than this repository needs; + # it is the cheapest way to keep the batch small enough to look at. + - cron: "0 6 * * 1" + workflow_dispatch: + +permissions: + issues: write + pull-requests: read + +jobs: + stale: + name: Sweep issues nobody has touched + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/stale@v9 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + + days-before-issue-stale: 90 + days-before-issue-close: 30 + stale-issue-label: stale + exempt-issue-labels: "bug,security,pinned,good first issue,help wanted" + + # Pull requests are out of scope. The ones that arrive here are mostly + # Dependabot's and are merged or closed within the day; a sweep would + # only ever catch one a person is still working on. + days-before-pr-stale: -1 + days-before-pr-close: -1 + + stale-issue-message: > + No activity here for three months, so this is marked stale. If it is + still relevant, a comment is enough to keep it open, and it will be + closed in a month otherwise. Nothing labelled bug, security or pinned + is ever marked this way, so if this is a defect that was never + labelled as one, say so and it will be. + + close-issue-message: > + Closed after four months without activity. This is housekeeping and + not a judgement: comment and it reopens, and the history stays here + either way. + + # The default. Small enough that a bad configuration cannot sweep the + # whole tracker before anyone notices. + operations-per-run: 30 diff --git a/.gitignore b/.gitignore index 36adf4d..a37c9f8 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,10 @@ *.swo /site/ .cache/ + +# cargo-mutants scratch output +/mutants.out/ +/mutants.out.old/ + +# macOS +.DS_Store diff --git a/100:T:0.9 b/100:T:0.9 deleted file mode 100644 index 2a9d361..0000000 --- a/100:T:0.9 +++ /dev/null @@ -1,2 +0,0 @@ -chr1 100 . A T . PASS . GT:DP:AD:ADR:FREQ 0/1:100:80:40:0.9 -chr1 100 . A T . PASS . GT:DP:AD:ADR:FREQ 0/1:100:80:40:0.9 diff --git a/200:G:0.9 b/200:G:0.9 deleted file mode 100644 index ad35bb9..0000000 --- a/200:G:0.9 +++ /dev/null @@ -1,2 +0,0 @@ -chr1 200 . A G . PASS . GT:DP:AD:ADR:FREQ 0/1:100:80:40:0.9 -chr1 200 . A G . PASS . GT:DP:AD:ADR:FREQ 0/1:100:80:40:0.9 diff --git a/300:C:0.9 b/300:C:0.9 deleted file mode 100644 index 0d16587..0000000 --- a/300:C:0.9 +++ /dev/null @@ -1,2 +0,0 @@ -chr1 300 . A C . PASS . GT:DP:AD:ADR:FREQ 0/1:100:80:40:0.9 -chr1 300 . A C . PASS . GT:DP:AD:ADR:FREQ 0/1:100:80:40:0.9 diff --git a/Cargo.lock b/Cargo.lock index 71a066b..e6400b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -147,9 +147,9 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" dependencies = [ "crossbeam-utils", ] diff --git a/Cargo.toml b/Cargo.toml index dc8c99b..2f3620d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,11 @@ name = "fstic" version = "1.0.1" edition = "2021" +# The floor is set by the dependency tree, not by this crate's own source: +# clap_lex requires edition2024, which needs 1.85. 1.84 fails to resolve at all. +# CI verifies this; keep it equal to the `toolchain:` input in +# .github/workflows/ci.yml. +rust-version = "1.85" authors = ["Paula Ruiz-Rodriguez "] description = "High-performance pairwise genetic distance calculator from allele-frequency data" license = "GPL-3.0" diff --git a/docs/about/contributing.md b/docs/about/contributing.md index 6b956c9..6a69289 100644 --- a/docs/about/contributing.md +++ b/docs/about/contributing.md @@ -70,7 +70,7 @@ all; the `off_diagonal` helper in `tests/integration.rs` exists for this. The site is MkDocs Material. ```bash -pip install -r requirements-docs.txt +pip install -r docs/requirements.txt mkdocs serve ``` diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 8827835..2fc1dd2 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -40,9 +40,12 @@ install -m 755 target/release/fstic ~/.local/bin/ !!! note "Rust version" - The crate uses the 2021 edition and `Option::is_none_or`, so it needs Rust - 1.82 or newer. `rustup update stable` if `cargo build` complains about an - unstable method. + Needs Rust **1.85** or newer, which is checked in CI on every pull request. + The floor comes from the dependency tree rather than from Fstic's own + source: `clap_lex` requires edition 2024. On 1.84 the build fails while + resolving, before it compiles anything. + + `rustup update stable` if `cargo build` complains about `edition2024`. ## Running the test suite diff --git a/requirements-docs.txt b/docs/requirements.txt similarity index 86% rename from requirements-docs.txt rename to docs/requirements.txt index 73843df..886a524 100644 --- a/requirements-docs.txt +++ b/docs/requirements.txt @@ -1,5 +1,5 @@ # Documentation site (MkDocs Material). Build locally with: -# pip install -r requirements-docs.txt +# pip install -r docs/requirements.txt # mkdocs serve # # mkdocs is pinned below 2.0: it drops the plugin system and theme overrides diff --git a/mkdocs.yml b/mkdocs.yml index e023b64..705d518 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -62,6 +62,11 @@ theme: - content.tabs.link - content.tooltips +# The docs build dependencies live in docs/ so Dependabot finds them next to +# what they build, but they are not a page and should not ship with the site. +exclude_docs: | + requirements.txt + # Broken cross-references and dead anchors become warnings, which `mkdocs build # --strict` in CI turns into a failed build. validation: diff --git a/src/calculation.rs b/src/calculation.rs index 439ba85..cef995e 100644 --- a/src/calculation.rs +++ b/src/calculation.rs @@ -1,14 +1,14 @@ +pub mod bray_curtis; +pub mod chord; pub mod common; pub mod fst; -#[cfg(test)] -mod tests; pub mod gst; -pub mod nei; -pub mod chord; -pub mod bray_curtis; pub mod jost_d; +pub mod nei; pub mod reynolds; pub mod rogers; +#[cfg(test)] +mod tests; pub fn generate_sample_pairs(samples: &[String]) -> Vec<(usize, usize)> { let n = samples.len(); @@ -24,7 +24,10 @@ pub fn generate_sample_pairs(samples: &[String]) -> Vec<(usize, usize)> { pairs } -pub fn create_distance_matrix(results: &[((usize, usize), f64)], num_samples: usize) -> Vec> { +pub fn create_distance_matrix( + results: &[((usize, usize), f64)], + num_samples: usize, +) -> Vec> { let mut matrix = vec![vec![0.0; num_samples]; num_samples]; for &((i, j), dist) in results { matrix[i][j] = dist; diff --git a/src/calculation/bray_curtis.rs b/src/calculation/bray_curtis.rs index 5fcd509..07606ec 100644 --- a/src/calculation/bray_curtis.rs +++ b/src/calculation/bray_curtis.rs @@ -13,13 +13,21 @@ pub fn calculate_bray_curtis_for_pair( ) -> f64 { let sum_dist = sum_per_locus(all_positions, |pos| { let psf = get_all_freqs_at_pos(data1.get(pos), data2.get(pos)); - let abs_diff: f64 = psf.all_alleles.iter().map(|a| { - let p = psf.freqs1.get(a).copied().unwrap_or(0.0); - let q = psf.freqs2.get(a).copied().unwrap_or(0.0); - (p - q).abs() - }).sum(); + let abs_diff: f64 = psf + .all_alleles + .iter() + .map(|a| { + let p = psf.freqs1.get(a).copied().unwrap_or(0.0); + let q = psf.freqs2.get(a).copied().unwrap_or(0.0); + (p - q).abs() + }) + .sum(); 0.5 * abs_diff }); - if normalize && num_loci > 0 { sum_dist / num_loci as f64 } else { sum_dist } + if normalize && num_loci > 0 { + sum_dist / num_loci as f64 + } else { + sum_dist + } } diff --git a/src/calculation/chord.rs b/src/calculation/chord.rs index 625127f..0cfb34c 100644 --- a/src/calculation/chord.rs +++ b/src/calculation/chord.rs @@ -14,14 +14,26 @@ pub fn calculate_chord_distance_for_pair( ) -> f64 { let sum_dist = sum_per_locus(all_positions, |pos| { let psf = get_all_freqs_at_pos(data1.get(pos), data2.get(pos)); - let sum_sqrt: f64 = psf.all_alleles.iter().map(|a| { - let p = psf.freqs1.get(a).copied().unwrap_or(0.0); - let q = psf.freqs2.get(a).copied().unwrap_or(0.0); - (p * q).sqrt() - }).sum(); + let sum_sqrt: f64 = psf + .all_alleles + .iter() + .map(|a| { + let p = psf.freqs1.get(a).copied().unwrap_or(0.0); + let q = psf.freqs2.get(a).copied().unwrap_or(0.0); + (p * q).sqrt() + }) + .sum(); let term = 2.0 * (1.0 - sum_sqrt); - if term > 0.0 { term.sqrt() } else { 0.0 } + if term > 0.0 { + term.sqrt() + } else { + 0.0 + } }); - if normalize && num_loci > 0 { sum_dist / num_loci as f64 } else { sum_dist } + if normalize && num_loci > 0 { + sum_dist / num_loci as f64 + } else { + sum_dist + } } diff --git a/src/calculation/common.rs b/src/calculation/common.rs index b85e77f..41fe058 100644 --- a/src/calculation/common.rs +++ b/src/calculation/common.rs @@ -88,7 +88,11 @@ pub fn get_all_freqs_at_pos( let ref_allele = site1_data .map(|d| &d.reference_allele) .filter(|r| !r.is_empty()) - .or_else(|| site2_data.map(|d| &d.reference_allele).filter(|r| !r.is_empty())) + .or_else(|| { + site2_data + .map(|d| &d.reference_allele) + .filter(|r| !r.is_empty()) + }) .cloned() .unwrap_or_else(|| UNKNOWN_REF.to_string()); diff --git a/src/calculation/fst.rs b/src/calculation/fst.rs index 58a0fcd..7bc3531 100644 --- a/src/calculation/fst.rs +++ b/src/calculation/fst.rs @@ -16,7 +16,11 @@ pub fn calculate_fst_for_pair( let psf = get_all_freqs_at_pos(data1.get(pos), data2.get(pos)); let h_s = (heterozygosity(&psf.freqs1) + heterozygosity(&psf.freqs2)) / 2.0; let h_t = pooled_heterozygosity(&psf); - if h_t > 0.0 { (h_t - h_s) / h_t } else { 0.0 } + if h_t > 0.0 { + (h_t - h_s) / h_t + } else { + 0.0 + } }); if normalize && num_loci > 0 { diff --git a/src/calculation/gst.rs b/src/calculation/gst.rs index f28d3be..56d6687 100644 --- a/src/calculation/gst.rs +++ b/src/calculation/gst.rs @@ -16,5 +16,9 @@ pub fn calculate_gst_for_pair( [h_t - h_s, h_t] }); - if total_den > 0.0 { total_num / total_den } else { 0.0 } + if total_den > 0.0 { + total_num / total_den + } else { + 0.0 + } } diff --git a/src/calculation/jost_d.rs b/src/calculation/jost_d.rs index 360c578..2952ad2 100644 --- a/src/calculation/jost_d.rs +++ b/src/calculation/jost_d.rs @@ -20,8 +20,16 @@ pub fn calculate_jost_d_for_pair( let h_s = (heterozygosity(&psf.freqs1) + heterozygosity(&psf.freqs2)) / 2.0; let h_t = pooled_heterozygosity(&psf); let denom = 1.0 - h_s; - if denom > 0.0 { correction * (h_t - h_s) / denom } else { 0.0 } + if denom > 0.0 { + correction * (h_t - h_s) / denom + } else { + 0.0 + } }); - if normalize && num_loci > 0 { sum_d / num_loci as f64 } else { sum_d } + if normalize && num_loci > 0 { + sum_d / num_loci as f64 + } else { + sum_d + } } diff --git a/src/calculation/nei.rs b/src/calculation/nei.rs index cef053e..e86b529 100644 --- a/src/calculation/nei.rs +++ b/src/calculation/nei.rs @@ -28,7 +28,11 @@ pub fn calculate_nei_distance_for_pair( let denom = (j_x * j_y).sqrt(); if denom > 0.0 { let identity = j_xy / denom; - if identity > 0.0 { -identity.ln() } else { f64::INFINITY } + if identity > 0.0 { + -identity.ln() + } else { + f64::INFINITY + } } else { f64::INFINITY } diff --git a/src/calculation/rogers.rs b/src/calculation/rogers.rs index 5e069d0..8cc483d 100644 --- a/src/calculation/rogers.rs +++ b/src/calculation/rogers.rs @@ -10,15 +10,20 @@ pub fn calculate_rogers_distance_for_pair( all_positions: &[GenomicPos], num_loci: usize, ) -> f64 { - if num_loci == 0 { return 0.0; } + if num_loci == 0 { + return 0.0; + } let total_sum_sq = sum_per_locus(all_positions, |pos| { let psf = get_all_freqs_at_pos(data1.get(pos), data2.get(pos)); - psf.all_alleles.iter().map(|a| { - let p = psf.freqs1.get(a).copied().unwrap_or(0.0); - let q = psf.freqs2.get(a).copied().unwrap_or(0.0); - (p - q).powi(2) - }).sum::() + psf.all_alleles + .iter() + .map(|a| { + let p = psf.freqs1.get(a).copied().unwrap_or(0.0); + let q = psf.freqs2.get(a).copied().unwrap_or(0.0); + (p - q).powi(2) + }) + .sum::() }); (total_sum_sq / (2.0 * num_loci as f64)).sqrt() diff --git a/src/calculation/tests.rs b/src/calculation/tests.rs index 53728bd..787dfda 100644 --- a/src/calculation/tests.rs +++ b/src/calculation/tests.rs @@ -1,682 +1,863 @@ -#[cfg(test)] -mod tests { - use crate::calculation::common::*; - use crate::types::{AlleleFrequencies, GenomicPos, PositionalData, SiteData}; - use std::collections::HashMap; - - fn gp(pos: usize) -> GenomicPos { - GenomicPos { chrom: "chr1".into(), pos } - } +use crate::calculation::common::*; +use crate::types::{AlleleFrequencies, GenomicPos, PositionalData, SiteData}; +use std::collections::HashMap; - fn make_site(ref_allele: &str, alts: &[(&str, f64)]) -> SiteData { - let mut freqs = AlleleFrequencies::new(); - for &(a, f) in alts { - freqs.insert(a.to_string(), f); - } - SiteData { reference_allele: ref_allele.to_string(), freqs } - } - - fn make_data(entries: &[(usize, &str, &[(&str, f64)])]) -> PositionalData { - let mut m = HashMap::new(); - for &(pos, ref_a, alts) in entries { - m.insert(gp(pos), make_site(ref_a, alts)); - } - m +fn gp(pos: usize) -> GenomicPos { + GenomicPos { + chrom: "chr1".into(), + pos, } +} - fn gps(poss: &[usize]) -> Vec { - poss.iter().map(|&p| gp(p)).collect() - } - - // ── get_all_freqs_at_pos ──────────────────────────────────────────── - - #[test] - fn freqs_ref_imputed() { - let site = make_site("A", &[("T", 0.3)]); - let psf = get_all_freqs_at_pos(Some(&site), None); - assert!((psf.freqs1["A"] - 0.7).abs() < 1e-10); - assert!((psf.freqs1["T"] - 0.3).abs() < 1e-10); - assert!((psf.freqs2["A"] - 1.0).abs() < 1e-10); +fn make_site(ref_allele: &str, alts: &[(&str, f64)]) -> SiteData { + let mut freqs = AlleleFrequencies::new(); + for &(a, f) in alts { + freqs.insert(a.to_string(), f); } - - #[test] - fn freqs_both_present() { - let s1 = make_site("A", &[("T", 0.4)]); - let s2 = make_site("A", &[("T", 0.6)]); - let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); - assert!((psf.freqs1["A"] - 0.6).abs() < 1e-10); - assert!((psf.freqs2["A"] - 0.4).abs() < 1e-10); + SiteData { + reference_allele: ref_allele.to_string(), + freqs, } +} - #[test] - fn freqs_clamp_negative_ref() { - let site = make_site("A", &[("T", 0.7), ("G", 0.4)]); - let psf = get_all_freqs_at_pos(Some(&site), None); - assert!(psf.freqs1["A"] >= 0.0); - } +/// (position, reference allele, [(alt allele, frequency)]). +type SiteSpec<'a> = (usize, &'a str, &'a [(&'a str, f64)]); - #[test] - fn freqs_no_ref() { - // REF unknown: the missing mass still has to go somewhere, so a placeholder - // reference allele carries it and the profile stays a distribution. - let s1 = SiteData { reference_allele: String::new(), freqs: { let mut f = AlleleFrequencies::new(); f.insert("T".into(), 0.5); f } }; - let psf = get_all_freqs_at_pos(Some(&s1), None); - assert_eq!(psf.freqs1.len(), 2); - let sum: f64 = psf.freqs1.values().sum(); - assert!((sum - 1.0).abs() < 1e-10); +fn make_data(entries: &[SiteSpec]) -> PositionalData { + let mut m = HashMap::new(); + for &(pos, ref_a, alts) in entries { + m.insert(gp(pos), make_site(ref_a, alts)); } + m +} - #[test] - fn freqs_both_none() { - // Site private to some other sample: both members of this pair are reference. - let psf = get_all_freqs_at_pos(None, None); - assert_eq!(psf.all_alleles.len(), 1); - let a = psf.all_alleles.iter().next().unwrap(); - assert!((psf.freqs1[a] - 1.0).abs() < 1e-10); - assert!((psf.freqs2[a] - 1.0).abs() < 1e-10); - } +fn gps(poss: &[usize]) -> Vec { + poss.iter().map(|&p| gp(p)).collect() +} - /// A locus where neither sample of the pair has a record is a locus where both are - /// reference, so it must add nothing to the cumulative metrics. Without this, a - /// pairwise distance changes when an unrelated sample joins the run. - /// - /// Nei's D and Rogers are excluded on purpose: both are defined over the whole - /// locus set (a ratio and a per-locus mean respectively), so a shared monomorphic - /// locus legitimately moves them. They are covered by - /// `identical_samples_zero_despite_foreign_loci` instead. - #[test] - fn absent_site_is_neutral_for_cumulative_metrics() { - let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); - let one = gps(&[100]); - // Position 999 is private to a third sample and absent from both d1 and d2. - let with_absent = gps(&[100, 999]); - - macro_rules! same { - ($a:expr, $b:expr, $name:literal) => { - assert!(($a - $b).abs() < 1e-10, "{} changed when an absent locus was added: {} vs {}", $name, $a, $b); - }; - } +// ── get_all_freqs_at_pos ──────────────────────────────────────────── - use crate::calculation::*; - same!(fst::calculate_fst_for_pair(&d1, &d2, &one, false, 1), - fst::calculate_fst_for_pair(&d1, &d2, &with_absent, false, 2), "fst"); - same!(gst::calculate_gst_for_pair(&d1, &d2, &one), - gst::calculate_gst_for_pair(&d1, &d2, &with_absent), "gst"); - same!(chord::calculate_chord_distance_for_pair(&d1, &d2, &one, false, 1), - chord::calculate_chord_distance_for_pair(&d1, &d2, &with_absent, false, 2), "chord"); - same!(bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &one, false, 1), - bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &with_absent, false, 2), "bray-curtis"); - same!(jost_d::calculate_jost_d_for_pair(&d1, &d2, &one, false, 1), - jost_d::calculate_jost_d_for_pair(&d1, &d2, &with_absent, false, 2), "jost_d"); - same!(reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &one), - reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &with_absent), "reynolds"); - } +#[test] +fn freqs_ref_imputed() { + let site = make_site("A", &[("T", 0.3)]); + let psf = get_all_freqs_at_pos(Some(&site), None); + assert!((psf.freqs1["A"] - 0.7).abs() < 1e-10); + assert!((psf.freqs1["T"] - 0.3).abs() < 1e-10); + assert!((psf.freqs2["A"] - 1.0).abs() < 1e-10); +} - /// A shared monomorphic locus is genetic identity, so it can only pull Nei's D - /// down, never up. - #[test] - fn absent_site_adds_identity_to_nei() { - let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); - let near = crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])); - let far = crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100, 999])); - assert!(far < near, "a shared monomorphic locus must reduce Nei's D: {} vs {}", far, near); - assert!(far > 0.0); - } +#[test] +fn freqs_both_present() { + let s1 = make_site("A", &[("T", 0.4)]); + let s2 = make_site("A", &[("T", 0.6)]); + let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); + assert!((psf.freqs1["A"] - 0.6).abs() < 1e-10); + assert!((psf.freqs2["A"] - 0.4).abs() < 1e-10); +} - /// Two identical samples must be at distance 0 no matter how many loci the rest - /// of the cohort contributes. - #[test] - fn identical_samples_zero_despite_foreign_loci() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[("T", 1.0)])]); - let p = gps(&[100, 200, 300, 400]); - assert!(crate::calculation::chord::calculate_chord_distance_for_pair(&d1, &d2, &p, false, 4).abs() < 1e-10); - assert!(crate::calculation::gst::calculate_gst_for_pair(&d1, &d2, &p).abs() < 1e-10); - assert!(crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &p, 4).abs() < 1e-10); - } +#[test] +fn freqs_clamp_negative_ref() { + let site = make_site("A", &[("T", 0.7), ("G", 0.4)]); + let psf = get_all_freqs_at_pos(Some(&site), None); + assert!(psf.freqs1["A"] >= 0.0); +} - #[test] - fn freqs_multiallelic() { - let s1 = make_site("A", &[("T", 0.3), ("G", 0.2)]); - let s2 = make_site("A", &[("T", 0.5)]); - let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); - assert_eq!(psf.all_alleles.len(), 3); - assert!((psf.freqs1["A"] - 0.5).abs() < 1e-10); - } +#[test] +fn freqs_no_ref() { + // REF unknown: the missing mass still has to go somewhere, so a placeholder + // reference allele carries it and the profile stays a distribution. + let s1 = SiteData { + reference_allele: String::new(), + freqs: { + let mut f = AlleleFrequencies::new(); + f.insert("T".into(), 0.5); + f + }, + }; + let psf = get_all_freqs_at_pos(Some(&s1), None); + assert_eq!(psf.freqs1.len(), 2); + let sum: f64 = psf.freqs1.values().sum(); + assert!((sum - 1.0).abs() < 1e-10); +} - // ── heterozygosity ────────────────────────────────────────────────── +#[test] +fn freqs_both_none() { + // Site private to some other sample: both members of this pair are reference. + let psf = get_all_freqs_at_pos(None, None); + assert_eq!(psf.all_alleles.len(), 1); + let a = psf.all_alleles.iter().next().unwrap(); + assert!((psf.freqs1[a] - 1.0).abs() < 1e-10); + assert!((psf.freqs2[a] - 1.0).abs() < 1e-10); +} - #[test] - fn het_monomorphic() { - let mut f = AlleleFrequencies::new(); f.insert("A".into(), 1.0); - assert!((heterozygosity(&f)).abs() < 1e-10); - assert!((homozygosity(&f) - 1.0).abs() < 1e-10); - } +/// A locus where neither sample of the pair has a record is a locus where both are +/// reference, so it must add nothing to the cumulative metrics. Without this, a +/// pairwise distance changes when an unrelated sample joins the run. +/// +/// Nei's D and Rogers are excluded on purpose: both are defined over the whole +/// locus set (a ratio and a per-locus mean respectively), so a shared monomorphic +/// locus legitimately moves them. They are covered by +/// `identical_samples_zero_despite_foreign_loci` instead. +#[test] +fn absent_site_is_neutral_for_cumulative_metrics() { + let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); + let one = gps(&[100]); + // Position 999 is private to a third sample and absent from both d1 and d2. + let with_absent = gps(&[100, 999]); + + macro_rules! same { + ($a:expr, $b:expr, $name:literal) => { + assert!( + ($a - $b).abs() < 1e-10, + "{} changed when an absent locus was added: {} vs {}", + $name, + $a, + $b + ); + }; + } + + use crate::calculation::*; + same!( + fst::calculate_fst_for_pair(&d1, &d2, &one, false, 1), + fst::calculate_fst_for_pair(&d1, &d2, &with_absent, false, 2), + "fst" + ); + same!( + gst::calculate_gst_for_pair(&d1, &d2, &one), + gst::calculate_gst_for_pair(&d1, &d2, &with_absent), + "gst" + ); + same!( + chord::calculate_chord_distance_for_pair(&d1, &d2, &one, false, 1), + chord::calculate_chord_distance_for_pair(&d1, &d2, &with_absent, false, 2), + "chord" + ); + same!( + bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &one, false, 1), + bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &with_absent, false, 2), + "bray-curtis" + ); + same!( + jost_d::calculate_jost_d_for_pair(&d1, &d2, &one, false, 1), + jost_d::calculate_jost_d_for_pair(&d1, &d2, &with_absent, false, 2), + "jost_d" + ); + same!( + reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &one), + reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &with_absent), + "reynolds" + ); +} - #[test] - fn het_biallelic() { - let mut f = AlleleFrequencies::new(); f.insert("A".into(), 0.5); f.insert("T".into(), 0.5); - assert!((heterozygosity(&f) - 0.5).abs() < 1e-10); - } +/// A shared monomorphic locus is genetic identity, so it can only pull Nei's D +/// down, never up. +#[test] +fn absent_site_adds_identity_to_nei() { + let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); + let near = crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])); + let far = crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100, 999])); + assert!( + far < near, + "a shared monomorphic locus must reduce Nei's D: {} vs {}", + far, + near + ); + assert!(far > 0.0); +} - #[test] - fn het_plus_hom() { - let mut f = AlleleFrequencies::new(); f.insert("A".into(), 0.7); f.insert("T".into(), 0.3); - assert!((heterozygosity(&f) + homozygosity(&f) - 1.0).abs() < 1e-10); - } +/// Two identical samples must be at distance 0 no matter how many loci the rest +/// of the cohort contributes. +#[test] +fn identical_samples_zero_despite_foreign_loci() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[("T", 1.0)])]); + let p = gps(&[100, 200, 300, 400]); + assert!( + crate::calculation::chord::calculate_chord_distance_for_pair(&d1, &d2, &p, false, 4).abs() + < 1e-10 + ); + assert!(crate::calculation::gst::calculate_gst_for_pair(&d1, &d2, &p).abs() < 1e-10); + assert!( + crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &p, 4).abs() + < 1e-10 + ); +} - // ── pooled_heterozygosity ─────────────────────────────────────────── +#[test] +fn freqs_multiallelic() { + let s1 = make_site("A", &[("T", 0.3), ("G", 0.2)]); + let s2 = make_site("A", &[("T", 0.5)]); + let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); + assert_eq!(psf.all_alleles.len(), 3); + assert!((psf.freqs1["A"] - 0.5).abs() < 1e-10); +} - #[test] - fn pooled_identical() { - let s1 = make_site("A", &[("T", 0.3)]); - let s2 = make_site("A", &[("T", 0.3)]); - let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); - let h_s = (heterozygosity(&psf.freqs1) + heterozygosity(&psf.freqs2)) / 2.0; - assert!((pooled_heterozygosity(&psf) - h_s).abs() < 1e-10); - } +// ── heterozygosity ────────────────────────────────────────────────── - #[test] - fn pooled_fixed_diff() { - let s1 = make_site("A", &[("T", 1.0)]); - let s2 = make_site("A", &[]); - let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); - assert!((pooled_heterozygosity(&psf) - 0.5).abs() < 1e-10); - } +#[test] +fn het_monomorphic() { + let mut f = AlleleFrequencies::new(); + f.insert("A".into(), 1.0); + assert!((heterozygosity(&f)).abs() < 1e-10); + assert!((homozygosity(&f) - 1.0).abs() < 1e-10); +} - // ── FST ───────────────────────────────────────────────────────────── +#[test] +fn het_biallelic() { + let mut f = AlleleFrequencies::new(); + f.insert("A".into(), 0.5); + f.insert("T".into(), 0.5); + assert!((heterozygosity(&f) - 0.5).abs() < 1e-10); +} - #[test] - fn fst_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.3)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); - let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!(fst.abs() < 1e-10); - } +#[test] +fn het_plus_hom() { + let mut f = AlleleFrequencies::new(); + f.insert("A".into(), 0.7); + f.insert("T".into(), 0.3); + assert!((heterozygosity(&f) + homozygosity(&f) - 1.0).abs() < 1e-10); +} - #[test] - fn fst_fixed_one() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!((fst - 1.0).abs() < 1e-10); - } +// ── pooled_heterozygosity ─────────────────────────────────────────── - #[test] - fn fst_normalized() { - let d1 = make_data(&[(100, "A", &[("T", 0.8)]), (200, "C", &[("G", 0.8)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.2)]), (200, "C", &[("G", 0.2)])]); - let raw = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100, 200]), false, 2); - let norm = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100, 200]), true, 2); - assert!((norm - raw / 2.0).abs() < 1e-10); - } +#[test] +fn pooled_identical() { + let s1 = make_site("A", &[("T", 0.3)]); + let s2 = make_site("A", &[("T", 0.3)]); + let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); + let h_s = (heterozygosity(&psf.freqs1) + heterozygosity(&psf.freqs2)) / 2.0; + assert!((pooled_heterozygosity(&psf) - h_s).abs() < 1e-10); +} - #[test] - fn fst_bounded() { - for af in &[0.0, 0.1, 0.5, 0.9, 1.0] { - let d1 = make_data(&[(100, "A", &[("T", *af)])]); - let d2 = make_data(&[(100, "A", &[("T", 1.0 - af)])]); - let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!(fst >= -1e-10 && fst <= 1.0 + 1e-10); - } - } +#[test] +fn pooled_fixed_diff() { + let s1 = make_site("A", &[("T", 1.0)]); + let s2 = make_site("A", &[]); + let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); + assert!((pooled_heterozygosity(&psf) - 0.5).abs() < 1e-10); +} - // ── GST ───────────────────────────────────────────────────────────── +// ── FST ───────────────────────────────────────────────────────────── - #[test] - fn gst_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); - assert!(crate::calculation::gst::calculate_gst_for_pair(&d1, &d2, &gps(&[100])).abs() < 1e-10); - } +#[test] +fn fst_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.3)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); + let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); + assert!(fst.abs() < 1e-10); +} - #[test] - fn gst_fixed_one() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - assert!((crate::calculation::gst::calculate_gst_for_pair(&d1, &d2, &gps(&[100])) - 1.0).abs() < 1e-10); - } +#[test] +fn fst_fixed_one() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); + assert!((fst - 1.0).abs() < 1e-10); +} - // ── Jost's D ──────────────────────────────────────────────────────── +#[test] +fn fst_normalized() { + let d1 = make_data(&[(100, "A", &[("T", 0.8)]), (200, "C", &[("G", 0.8)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.2)]), (200, "C", &[("G", 0.2)])]); + let raw = + crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100, 200]), false, 2); + let norm = + crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100, 200]), true, 2); + assert!((norm - raw / 2.0).abs() < 1e-10); +} - #[test] - fn jost_d_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.3)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); - assert!(crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1).abs() < 1e-10); +#[test] +fn fst_bounded() { + for af in &[0.0, 0.1, 0.5, 0.9, 1.0] { + let d1 = make_data(&[(100, "A", &[("T", *af)])]); + let d2 = make_data(&[(100, "A", &[("T", 1.0 - af)])]); + let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); + assert!((-1e-10..=1.0 + 1e-10).contains(&fst)); } +} - #[test] - fn jost_d_fixed_one() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - assert!((crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1) - 1.0).abs() < 1e-10); - } +// ── GST ───────────────────────────────────────────────────────────── - #[test] - fn jost_d_non_negative() { - for af1 in &[0.0, 0.3, 0.5, 0.7, 1.0] { - for af2 in &[0.0, 0.3, 0.5, 0.7, 1.0] { - let d1 = make_data(&[(100, "A", &[("T", *af1)])]); - let d2 = make_data(&[(100, "A", &[("T", *af2)])]); - let d = crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!(d >= -1e-10); - } - } - } +#[test] +fn gst_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); + assert!(crate::calculation::gst::calculate_gst_for_pair(&d1, &d2, &gps(&[100])).abs() < 1e-10); +} - #[test] - fn jost_d_symmetric() { - let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); - let a = crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1); - let b = crate::calculation::jost_d::calculate_jost_d_for_pair(&d2, &d1, &gps(&[100]), false, 1); - assert!((a - b).abs() < 1e-10); - } +#[test] +fn gst_fixed_one() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + assert!( + (crate::calculation::gst::calculate_gst_for_pair(&d1, &d2, &gps(&[100])) - 1.0).abs() + < 1e-10 + ); +} - // ── Nei ───────────────────────────────────────────────────────────── +// ── Jost's D ──────────────────────────────────────────────────────── + +#[test] +fn jost_d_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.3)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); + assert!( + crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1) + .abs() + < 1e-10 + ); +} - #[test] - fn nei_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.4)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.4)])]); - assert!(crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])).abs() < 1e-10); - } +#[test] +fn jost_d_fixed_one() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + assert!( + (crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1) + - 1.0) + .abs() + < 1e-10 + ); +} - #[test] - fn nei_fixed_inf() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - assert!(crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])).is_infinite()); +#[test] +fn jost_d_non_negative() { + for af1 in &[0.0, 0.3, 0.5, 0.7, 1.0] { + for af2 in &[0.0, 0.3, 0.5, 0.7, 1.0] { + let d1 = make_data(&[(100, "A", &[("T", *af1)])]); + let d2 = make_data(&[(100, "A", &[("T", *af2)])]); + let d = crate::calculation::jost_d::calculate_jost_d_for_pair( + &d1, + &d2, + &gps(&[100]), + false, + 1, + ); + assert!(d >= -1e-10); + } } +} - #[test] - fn nei_symmetric() { - let d1 = make_data(&[(100, "A", &[("T", 0.8)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); - let a = crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])); - let b = crate::calculation::nei::calculate_nei_distance_for_pair(&d2, &d1, &gps(&[100])); - assert!((a - b).abs() < 1e-10); - } +#[test] +fn jost_d_symmetric() { + let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); + let a = crate::calculation::jost_d::calculate_jost_d_for_pair(&d1, &d2, &gps(&[100]), false, 1); + let b = crate::calculation::jost_d::calculate_jost_d_for_pair(&d2, &d1, &gps(&[100]), false, 1); + assert!((a - b).abs() < 1e-10); +} - // ── Chord ─────────────────────────────────────────────────────────── +// ── Nei ───────────────────────────────────────────────────────────── - #[test] - fn chord_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); - assert!(crate::calculation::chord::calculate_chord_distance_for_pair(&d1, &d2, &gps(&[100]), false, 1).abs() < 1e-10); - } +#[test] +fn nei_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.4)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.4)])]); + assert!( + crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])).abs() + < 1e-10 + ); +} - #[test] - fn chord_fixed() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - let d = crate::calculation::chord::calculate_chord_distance_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!((d - 2.0_f64.sqrt()).abs() < 1e-10); - } +#[test] +fn nei_fixed_inf() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + assert!( + crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])) + .is_infinite() + ); +} - // ── Bray-Curtis ───────────────────────────────────────────────────── +#[test] +fn nei_symmetric() { + let d1 = make_data(&[(100, "A", &[("T", 0.8)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); + let a = crate::calculation::nei::calculate_nei_distance_for_pair(&d1, &d2, &gps(&[100])); + let b = crate::calculation::nei::calculate_nei_distance_for_pair(&d2, &d1, &gps(&[100])); + assert!((a - b).abs() < 1e-10); +} - #[test] - fn bc_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.3)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); - assert!(crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &gps(&[100]), false, 1).abs() < 1e-10); - } +// ── Chord ─────────────────────────────────────────────────────────── + +#[test] +fn chord_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); + assert!( + crate::calculation::chord::calculate_chord_distance_for_pair( + &d1, + &d2, + &gps(&[100]), + false, + 1 + ) + .abs() + < 1e-10 + ); +} - #[test] - fn bc_fixed() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - assert!((crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &gps(&[100]), false, 1) - 1.0).abs() < 1e-10); - } +#[test] +fn chord_fixed() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + let d = crate::calculation::chord::calculate_chord_distance_for_pair( + &d1, + &d2, + &gps(&[100]), + false, + 1, + ); + assert!((d - 2.0_f64.sqrt()).abs() < 1e-10); +} - #[test] - fn bc_bounded() { - for af in &[0.0, 0.2, 0.5, 0.8, 1.0] { - let d1 = make_data(&[(100, "A", &[("T", *af)])]); - let d2 = make_data(&[(100, "A", &[("T", 1.0 - af)])]); - let d = crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!(d >= -1e-10 && d <= 1.0 + 1e-10); - } - } +// ── Bray-Curtis ───────────────────────────────────────────────────── + +#[test] +fn bc_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.3)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.3)])]); + assert!( + crate::calculation::bray_curtis::calculate_bray_curtis_for_pair( + &d1, + &d2, + &gps(&[100]), + false, + 1 + ) + .abs() + < 1e-10 + ); +} - // ── Reynolds ──────────────────────────────────────────────────────── +#[test] +fn bc_fixed() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + assert!( + (crate::calculation::bray_curtis::calculate_bray_curtis_for_pair( + &d1, + &d2, + &gps(&[100]), + false, + 1 + ) - 1.0) + .abs() + < 1e-10 + ); +} - #[test] - fn reynolds_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); - assert!(crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &gps(&[100])).abs() < 1e-10); +#[test] +fn bc_bounded() { + for af in &[0.0, 0.2, 0.5, 0.8, 1.0] { + let d1 = make_data(&[(100, "A", &[("T", *af)])]); + let d2 = make_data(&[(100, "A", &[("T", 1.0 - af)])]); + let d = crate::calculation::bray_curtis::calculate_bray_curtis_for_pair( + &d1, + &d2, + &gps(&[100]), + false, + 1, + ); + assert!((-1e-10..=1.0 + 1e-10).contains(&d)); } +} - #[test] - fn reynolds_fixed_inf() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - assert!(crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &gps(&[100])).is_infinite()); - } +// ── Reynolds ──────────────────────────────────────────────────────── + +#[test] +fn reynolds_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); + assert!( + crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &gps(&[100])) + .abs() + < 1e-10 + ); +} - /// At intermediate frequencies the coancestry estimator and Nei's GST diverge, so - /// this is the case that tells them apart. Substituting GST would give 0.4054651. - #[test] - fn reynolds_uses_coancestry_not_gst() { - // p = {T:0.5, A:0.5} vs q = {T:1.0, A:0.0} - // theta = ((0.5)^2 + (0.5)^2)/2 / (1 - 0.5) = 0.25/0.5 = 0.5 - let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); - let d2 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d = crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &gps(&[100])); - assert!((d - (2.0_f64).ln()).abs() < 1e-10, "expected -ln(0.5), got {}", d); - } +#[test] +fn reynolds_fixed_inf() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + assert!( + crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &gps(&[100])) + .is_infinite() + ); +} - #[test] - fn reynolds_symmetric() { - let d1 = make_data(&[(100, "A", &[("T", 0.7)]), (200, "C", &[("G", 0.1)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.2)]), (200, "C", &[("G", 0.9)])]); - let p = gps(&[100, 200]); - let a = crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &p); - let b = crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d2, &d1, &p); - assert!((a - b).abs() < 1e-10); - assert!(a > 0.0); - } +/// At intermediate frequencies the coancestry estimator and Nei's GST diverge, so +/// this is the case that tells them apart. Substituting GST would give 0.4054651. +#[test] +fn reynolds_uses_coancestry_not_gst() { + // p = {T:0.5, A:0.5} vs q = {T:1.0, A:0.0} + // theta = ((0.5)^2 + (0.5)^2)/2 / (1 - 0.5) = 0.25/0.5 = 0.5 + let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); + let d2 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d = + crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &gps(&[100])); + assert!( + (d - (2.0_f64).ln()).abs() < 1e-10, + "expected -ln(0.5), got {}", + d + ); +} - // ── Rogers ────────────────────────────────────────────────────────── +#[test] +fn reynolds_symmetric() { + let d1 = make_data(&[(100, "A", &[("T", 0.7)]), (200, "C", &[("G", 0.1)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.2)]), (200, "C", &[("G", 0.9)])]); + let p = gps(&[100, 200]); + let a = crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d1, &d2, &p); + let b = crate::calculation::reynolds::calculate_reynolds_distance_for_pair(&d2, &d1, &p); + assert!((a - b).abs() < 1e-10); + assert!(a > 0.0); +} - #[test] - fn rogers_identical_zero() { - let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); - assert!(crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &gps(&[100]), 1).abs() < 1e-10); - } +// ── Rogers ────────────────────────────────────────────────────────── + +#[test] +fn rogers_identical_zero() { + let d1 = make_data(&[(100, "A", &[("T", 0.5)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.5)])]); + assert!( + crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &gps(&[100]), 1) + .abs() + < 1e-10 + ); +} - #[test] - fn rogers_fixed() { - let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); - let d2 = make_data(&[(100, "A", &[])]); - assert!((crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &gps(&[100]), 1) - 1.0).abs() < 1e-10); - } +#[test] +fn rogers_fixed() { + let d1 = make_data(&[(100, "A", &[("T", 1.0)])]); + let d2 = make_data(&[(100, "A", &[])]); + assert!( + (crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &gps(&[100]), 1) + - 1.0) + .abs() + < 1e-10 + ); +} - #[test] - fn rogers_bounded() { - for af in &[0.0, 0.2, 0.5, 0.8, 1.0] { - let d1 = make_data(&[(100, "A", &[("T", *af)])]); - let d2 = make_data(&[(100, "A", &[("T", 1.0 - af)])]); - let d = crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &gps(&[100]), 1); - assert!(d >= -1e-10 && d <= 1.0 + 1e-10); - } +#[test] +fn rogers_bounded() { + for af in &[0.0, 0.2, 0.5, 0.8, 1.0] { + let d1 = make_data(&[(100, "A", &[("T", *af)])]); + let d2 = make_data(&[(100, "A", &[("T", 1.0 - af)])]); + let d = crate::calculation::rogers::calculate_rogers_distance_for_pair( + &d1, + &d2, + &gps(&[100]), + 1, + ); + assert!((-1e-10..=1.0 + 1e-10).contains(&d)); } +} - // ── Utility ───────────────────────────────────────────────────────── +// ── Utility ───────────────────────────────────────────────────────── - #[test] - fn pairs_count() { - let s: Vec = (0..5).map(|i| format!("s{}", i)).collect(); - assert_eq!(crate::calculation::generate_sample_pairs(&s).len(), 10); - } - - #[test] - fn pairs_empty() { assert!(crate::calculation::generate_sample_pairs(&[]).is_empty()); } - - #[test] - fn pairs_single() { assert!(crate::calculation::generate_sample_pairs(&["s1".into()]).is_empty()); } - - #[test] - fn matrix_symmetric() { - let r = vec![((0, 1), 0.5), ((0, 2), 0.3), ((1, 2), 0.7)]; - let m = crate::calculation::create_distance_matrix(&r, 3); - - // m[0][1] == m[1][0] holds even if both cells hold the wrong number, so check - // the values that went in actually came back out. - assert_eq!(m[0][1], 0.5); - assert_eq!(m[1][0], 0.5); - assert_eq!(m[0][2], 0.3); - assert_eq!(m[2][0], 0.3); - assert_eq!(m[1][2], 0.7); - assert_eq!(m[2][1], 0.7); - for (i, row) in m.iter().enumerate() { - assert_eq!(row[i], 0.0, "diagonal at {}", i); - } - } +#[test] +fn pairs_count() { + let s: Vec = (0..5).map(|i| format!("s{}", i)).collect(); + assert_eq!(crate::calculation::generate_sample_pairs(&s).len(), 10); +} - #[test] - fn quote_field_protects_separators() { - use crate::io::csv::write_distance_matrix; - let dir = tempfile::tempdir().unwrap(); - let out = dir.path().join("out.csv"); - let m = vec![vec![0.0, 0.5], vec![0.5, 0.0]]; - let samples = vec!["with,comma".to_string(), "he said \"hi\"".to_string()]; - write_distance_matrix(out.to_str().unwrap(), &m, &samples, false).unwrap(); - - let c = std::fs::read_to_string(&out).unwrap(); - assert!(c.contains("\"with,comma\""), "got: {}", c); - // Embedded quotes are doubled, per RFC 4180 - assert!(c.contains("\"he said \"\"hi\"\"\""), "got: {}", c); - } +#[test] +fn pairs_empty() { + assert!(crate::calculation::generate_sample_pairs(&[]).is_empty()); +} - #[test] - fn non_finite_cells_written_as_na() { - use crate::io::csv::write_distance_matrix; - let dir = tempfile::tempdir().unwrap(); - let out = dir.path().join("out.csv"); - let m = vec![ - vec![0.0, f64::INFINITY], - vec![f64::INFINITY, 0.0], - ]; - write_distance_matrix(out.to_str().unwrap(), &m, &["A".into(), "B".into()], false).unwrap(); - - let c = std::fs::read_to_string(&out).unwrap(); - assert!(c.contains("A,0.0000000000,NA"), "got: {}", c); - assert!(!c.to_lowercase().contains("inf"), "got: {}", c); - } +#[test] +fn pairs_single() { + assert!(crate::calculation::generate_sample_pairs(&["s1".into()]).is_empty()); +} - #[test] - fn fst_multi_locus() { - let d1 = make_data(&[(100, "A", &[("T", 0.9)]), (200, "C", &[("G", 0.1)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.1)]), (200, "C", &[("G", 0.9)])]); - let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100, 200]), false, 2); - let single = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); - assert!((fst - 2.0 * single).abs() < 1e-10); +#[test] +fn matrix_symmetric() { + let r = vec![((0, 1), 0.5), ((0, 2), 0.3), ((1, 2), 0.7)]; + let m = crate::calculation::create_distance_matrix(&r, 3); + + // m[0][1] == m[1][0] holds even if both cells hold the wrong number, so check + // the values that went in actually came back out. + assert_eq!(m[0][1], 0.5); + assert_eq!(m[1][0], 0.5); + assert_eq!(m[0][2], 0.3); + assert_eq!(m[2][0], 0.3); + assert_eq!(m[1][2], 0.7); + assert_eq!(m[2][1], 0.7); + for (i, row) in m.iter().enumerate() { + assert_eq!(row[i], 0.0, "diagonal at {}", i); } +} - // ── Multi-chrom correctness ───────────────────────────────────────── - - #[test] - fn different_chroms_are_distinct_sites() { - let pos_a = GenomicPos { chrom: "chr1".into(), pos: 100 }; - let pos_b = GenomicPos { chrom: "chr2".into(), pos: 100 }; - assert_ne!(pos_a, pos_b); +#[test] +fn quote_field_protects_separators() { + use crate::io::csv::write_distance_matrix; + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("out.csv"); + let m = vec![vec![0.0, 0.5], vec![0.5, 0.0]]; + let samples = vec!["with,comma".to_string(), "he said \"hi\"".to_string()]; + write_distance_matrix(out.to_str().unwrap(), &m, &samples, false).unwrap(); + + let c = std::fs::read_to_string(&out).unwrap(); + assert!(c.contains("\"with,comma\""), "got: {}", c); + // Embedded quotes are doubled, per RFC 4180 + assert!(c.contains("\"he said \"\"hi\"\"\""), "got: {}", c); +} - // Same position number on different chroms should be independent - let mut d1 = PositionalData::new(); - d1.insert(pos_a.clone(), make_site("A", &[("T", 0.9)])); - d1.insert(pos_b.clone(), make_site("C", &[("G", 0.1)])); +#[test] +fn non_finite_cells_written_as_na() { + use crate::io::csv::write_distance_matrix; + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("out.csv"); + let m = vec![vec![0.0, f64::INFINITY], vec![f64::INFINITY, 0.0]]; + write_distance_matrix(out.to_str().unwrap(), &m, &["A".into(), "B".into()], false).unwrap(); + + let c = std::fs::read_to_string(&out).unwrap(); + assert!(c.contains("A,0.0000000000,NA"), "got: {}", c); + assert!(!c.to_lowercase().contains("inf"), "got: {}", c); +} - let mut d2 = PositionalData::new(); - d2.insert(pos_a.clone(), make_site("A", &[("T", 0.1)])); - d2.insert(pos_b.clone(), make_site("C", &[("G", 0.9)])); +#[test] +fn fst_multi_locus() { + let d1 = make_data(&[(100, "A", &[("T", 0.9)]), (200, "C", &[("G", 0.1)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.1)]), (200, "C", &[("G", 0.9)])]); + let fst = + crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100, 200]), false, 2); + let single = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &gps(&[100]), false, 1); + assert!((fst - 2.0 * single).abs() < 1e-10); +} - let positions = vec![pos_a, pos_b]; - let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &positions, false, 2); - assert!(fst > 0.0, "Different chroms should contribute independently"); - } +// ── Multi-chrom correctness ───────────────────────────────────────── + +#[test] +fn different_chroms_are_distinct_sites() { + let pos_a = GenomicPos { + chrom: "chr1".into(), + pos: 100, + }; + let pos_b = GenomicPos { + chrom: "chr2".into(), + pos: 100, + }; + assert_ne!(pos_a, pos_b); + + // Same position number on different chroms should be independent + let mut d1 = PositionalData::new(); + d1.insert(pos_a.clone(), make_site("A", &[("T", 0.9)])); + d1.insert(pos_b.clone(), make_site("C", &[("G", 0.1)])); + + let mut d2 = PositionalData::new(); + d2.insert(pos_a.clone(), make_site("A", &[("T", 0.1)])); + d2.insert(pos_b.clone(), make_site("C", &[("G", 0.9)])); + + let positions = vec![pos_a, pos_b]; + let fst = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &positions, false, 2); + assert!( + fst > 0.0, + "Different chroms should contribute independently" + ); +} - // ── FASTA ─────────────────────────────────────────────────────────── - - #[test] - fn fasta_multi_contig() { - let dir = tempfile::tempdir().unwrap(); - let p = dir.path().join("ref.fa"); - std::fs::write(&p, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap(); - let g = crate::io::fasta::read_reference(p.to_str().unwrap()).unwrap(); - assert_eq!(g.len(), 2); - assert_eq!(g["chr1"], b"ACGT"); - assert_eq!(g["chr2"], b"TTTT"); - } +// ── FASTA ─────────────────────────────────────────────────────────── + +#[test] +fn fasta_multi_contig() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("ref.fa"); + std::fs::write(&p, ">chr1\nACGT\n>chr2\nTTTT\n").unwrap(); + let g = crate::io::fasta::read_reference(p.to_str().unwrap()).unwrap(); + assert_eq!(g.len(), 2); + assert_eq!(g["chr1"], b"ACGT"); + assert_eq!(g["chr2"], b"TTTT"); +} - #[test] - fn fasta_deterministic() { - let dir = tempfile::tempdir().unwrap(); - let p = dir.path().join("ref.fa"); - std::fs::write(&p, ">z_last\nGGGG\n>a_first\nACGT\n").unwrap(); - let g = crate::io::fasta::read_reference(p.to_str().unwrap()).unwrap(); - let names: Vec<&str> = g.keys().map(|s| s.as_str()).collect(); - assert_eq!(names, vec!["a_first", "z_last"]); - } +#[test] +fn fasta_deterministic() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("ref.fa"); + std::fs::write(&p, ">z_last\nGGGG\n>a_first\nACGT\n").unwrap(); + let g = crate::io::fasta::read_reference(p.to_str().unwrap()).unwrap(); + let names: Vec<&str> = g.keys().map(|s| s.as_str()).collect(); + assert_eq!(names, vec!["a_first", "z_last"]); +} - #[test] - fn fasta_softmasked_uppercase() { - let dir = tempfile::tempdir().unwrap(); - let p = dir.path().join("ref.fa"); - std::fs::write(&p, ">chr1\nacgt\nNNnn\n").unwrap(); - let g = crate::io::fasta::read_reference(p.to_str().unwrap()).unwrap(); - assert_eq!(g["chr1"], b"ACGTNNNN"); - } +#[test] +fn fasta_softmasked_uppercase() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("ref.fa"); + std::fs::write(&p, ">chr1\nacgt\nNNnn\n").unwrap(); + let g = crate::io::fasta::read_reference(p.to_str().unwrap()).unwrap(); + assert_eq!(g["chr1"], b"ACGTNNNN"); +} - #[test] - fn fasta_empty() { - let dir = tempfile::tempdir().unwrap(); - let p = dir.path().join("empty.fa"); - std::fs::write(&p, "").unwrap(); - assert!(crate::io::fasta::read_reference(p.to_str().unwrap()).is_err()); - } +#[test] +fn fasta_empty() { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("empty.fa"); + std::fs::write(&p, "").unwrap(); + assert!(crate::io::fasta::read_reference(p.to_str().unwrap()).is_err()); +} - fn read_fa(body: &str) -> Result { - let dir = tempfile::tempdir().unwrap(); - let p = dir.path().join("ref.fa"); - std::fs::write(&p, body).unwrap(); - crate::io::fasta::read_reference(p.to_str().unwrap()) - } +fn read_fa(body: &str) -> Result { + let dir = tempfile::tempdir().unwrap(); + let p = dir.path().join("ref.fa"); + std::fs::write(&p, body).unwrap(); + crate::io::fasta::read_reference(p.to_str().unwrap()) +} - #[test] - fn fasta_nameless_record_rejected() { - // Used to leave current_name empty, so the nameless record's bases were - // prepended to the next contig and shifted every coordinate after it. - assert!(read_fa(">\nAAAA\n>chr1\nCCCC\n").is_err()); - } +#[test] +fn fasta_nameless_record_rejected() { + // Used to leave current_name empty, so the nameless record's bases were + // prepended to the next contig and shifted every coordinate after it. + assert!(read_fa(">\nAAAA\n>chr1\nCCCC\n").is_err()); +} - #[test] - fn fasta_sequence_before_header_rejected() { - assert!(read_fa("AAAA\n>chr1\nCCCC\n").is_err()); - } +#[test] +fn fasta_sequence_before_header_rejected() { + assert!(read_fa("AAAA\n>chr1\nCCCC\n").is_err()); +} - #[test] - fn fasta_duplicate_contig_rejected() { - assert!(read_fa(">chr1\nAAAA\n>chr1\nCCCC\n").is_err()); - } +#[test] +fn fasta_duplicate_contig_rejected() { + assert!(read_fa(">chr1\nAAAA\n>chr1\nCCCC\n").is_err()); +} - #[test] - fn fasta_records_stay_separate() { - let g = read_fa(">chr1 description here\nAA\nAA\n>chr2\nCCCC\n").unwrap(); - assert_eq!(g["chr1"], b"AAAA"); - assert_eq!(g["chr2"], b"CCCC"); - } +#[test] +fn fasta_records_stay_separate() { + let g = read_fa(">chr1 description here\nAA\nAA\n>chr2\nCCCC\n").unwrap(); + assert_eq!(g["chr1"], b"AAAA"); + assert_eq!(g["chr2"], b"CCCC"); +} - // ── Frequency renormalisation ─────────────────────────────────────── - - #[test] - fn saturated_site_is_rescaled() { - // Split multi-allelic records: two independently estimated 0.9 frequencies. - let mut sv = crate::types::SampleVariants::new(); - sv.insert("s1".to_string(), make_data(&[(100, "A", &[("T", 0.9), ("G", 0.9)])])); - assert_eq!(crate::io::renormalise_saturated_sites(&mut sv), 1); - - let freqs = &sv["s1"][&gp(100)].freqs; - let sum: f64 = freqs.values().sum(); - assert!((sum - 1.0).abs() < 1e-10, "sum is {}", sum); - assert!((freqs["T"] - 0.5).abs() < 1e-10); - // Heterozygosity must be back in [0,1] - let h = heterozygosity(freqs); - assert!((0.0..=1.0).contains(&h), "heterozygosity is {}", h); - } +// ── Frequency renormalisation ─────────────────────────────────────── + +#[test] +fn saturated_site_is_rescaled() { + // Split multi-allelic records: two independently estimated 0.9 frequencies. + let mut sv = crate::types::SampleVariants::new(); + sv.insert( + "s1".to_string(), + make_data(&[(100, "A", &[("T", 0.9), ("G", 0.9)])]), + ); + assert_eq!(crate::io::renormalise_saturated_sites(&mut sv), 1); + + let freqs = &sv["s1"][&gp(100)].freqs; + let sum: f64 = freqs.values().sum(); + assert!((sum - 1.0).abs() < 1e-10, "sum is {}", sum); + assert!((freqs["T"] - 0.5).abs() < 1e-10); + // Heterozygosity must be back in [0,1] + let h = heterozygosity(freqs); + assert!((0.0..=1.0).contains(&h), "heterozygosity is {}", h); +} - #[test] - fn well_formed_sites_are_left_alone() { - let mut sv = crate::types::SampleVariants::new(); - sv.insert("s1".to_string(), make_data(&[(100, "A", &[("T", 0.3)]), (200, "C", &[("G", 1.0)])])); - assert_eq!(crate::io::renormalise_saturated_sites(&mut sv), 0); - assert!((sv["s1"][&gp(100)].freqs["T"] - 0.3).abs() < 1e-10); - } +#[test] +fn well_formed_sites_are_left_alone() { + let mut sv = crate::types::SampleVariants::new(); + sv.insert( + "s1".to_string(), + make_data(&[(100, "A", &[("T", 0.3)]), (200, "C", &[("G", 1.0)])]), + ); + assert_eq!(crate::io::renormalise_saturated_sites(&mut sv), 0); + assert!((sv["s1"][&gp(100)].freqs["T"] - 0.3).abs() < 1e-10); +} - #[test] - fn rounding_noise_is_not_rescaled() { - let mut sv = crate::types::SampleVariants::new(); - sv.insert("s1".to_string(), make_data(&[(100, "A", &[("T", 1.0 + 1e-12)])])); - assert_eq!(crate::io::renormalise_saturated_sites(&mut sv), 0); - } +#[test] +fn rounding_noise_is_not_rescaled() { + let mut sv = crate::types::SampleVariants::new(); + sv.insert( + "s1".to_string(), + make_data(&[(100, "A", &[("T", 1.0 + 1e-12)])]), + ); + assert_eq!(crate::io::renormalise_saturated_sites(&mut sv), 0); +} - // ── All symmetric ─────────────────────────────────────────────────── +// ── All symmetric ─────────────────────────────────────────────────── - #[test] - fn all_metrics_symmetric() { - let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); - let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); - let p = gps(&[100]); +#[test] +fn all_metrics_symmetric() { + let d1 = make_data(&[(100, "A", &[("T", 0.7)])]); + let d2 = make_data(&[(100, "A", &[("T", 0.2)])]); + let p = gps(&[100]); - let f12 = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &p, false, 1); - let f21 = crate::calculation::fst::calculate_fst_for_pair(&d2, &d1, &p, false, 1); - assert!((f12 - f21).abs() < 1e-10); + let f12 = crate::calculation::fst::calculate_fst_for_pair(&d1, &d2, &p, false, 1); + let f21 = crate::calculation::fst::calculate_fst_for_pair(&d2, &d1, &p, false, 1); + assert!((f12 - f21).abs() < 1e-10); - let b12 = crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &p, false, 1); - let b21 = crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d2, &d1, &p, false, 1); - assert!((b12 - b21).abs() < 1e-10); + let b12 = + crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d1, &d2, &p, false, 1); + let b21 = + crate::calculation::bray_curtis::calculate_bray_curtis_for_pair(&d2, &d1, &p, false, 1); + assert!((b12 - b21).abs() < 1e-10); - let c12 = crate::calculation::chord::calculate_chord_distance_for_pair(&d1, &d2, &p, false, 1); - let c21 = crate::calculation::chord::calculate_chord_distance_for_pair(&d2, &d1, &p, false, 1); - assert!((c12 - c21).abs() < 1e-10); + let c12 = crate::calculation::chord::calculate_chord_distance_for_pair(&d1, &d2, &p, false, 1); + let c21 = crate::calculation::chord::calculate_chord_distance_for_pair(&d2, &d1, &p, false, 1); + assert!((c12 - c21).abs() < 1e-10); - let r12 = crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &p, 1); - let r21 = crate::calculation::rogers::calculate_rogers_distance_for_pair(&d2, &d1, &p, 1); - assert!((r12 - r21).abs() < 1e-10); - } + let r12 = crate::calculation::rogers::calculate_rogers_distance_for_pair(&d1, &d2, &p, 1); + let r21 = crate::calculation::rogers::calculate_rogers_distance_for_pair(&d2, &d1, &p, 1); + assert!((r12 - r21).abs() < 1e-10); +} - // ── Output format ─────────────────────────────────────────────────── - - #[test] - fn write_csv() { - let dir = tempfile::tempdir().unwrap(); - let out = dir.path().join("out.csv"); - let m = vec![vec![0.0, 0.5], vec![0.5, 0.0]]; - crate::io::csv::write_distance_matrix(out.to_str().unwrap(), &m, &["A".into(), "B".into()], false).unwrap(); - let c = std::fs::read_to_string(&out).unwrap(); - assert!(c.starts_with("sample,")); - assert!(c.contains("A,0.0000000000,0.5000000000")); - } +// ── Output format ─────────────────────────────────────────────────── + +#[test] +fn write_csv() { + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("out.csv"); + let m = vec![vec![0.0, 0.5], vec![0.5, 0.0]]; + crate::io::csv::write_distance_matrix( + out.to_str().unwrap(), + &m, + &["A".into(), "B".into()], + false, + ) + .unwrap(); + let c = std::fs::read_to_string(&out).unwrap(); + assert!(c.starts_with("sample,")); + assert!(c.contains("A,0.0000000000,0.5000000000")); +} - #[test] - fn write_tsv() { - let dir = tempfile::tempdir().unwrap(); - let out = dir.path().join("out.tsv"); - let m = vec![vec![0.0, 0.5], vec![0.5, 0.0]]; - crate::io::csv::write_distance_matrix(out.to_str().unwrap(), &m, &["A".into(), "B".into()], true).unwrap(); - let c = std::fs::read_to_string(&out).unwrap(); - assert!(c.starts_with("sample\t")); - } +#[test] +fn write_tsv() { + let dir = tempfile::tempdir().unwrap(); + let out = dir.path().join("out.tsv"); + let m = vec![vec![0.0, 0.5], vec![0.5, 0.0]]; + crate::io::csv::write_distance_matrix( + out.to_str().unwrap(), + &m, + &["A".into(), "B".into()], + true, + ) + .unwrap(); + let c = std::fs::read_to_string(&out).unwrap(); + assert!(c.starts_with("sample\t")); +} - // ── Ref imputation does not overwrite explicit freq ────────────── - - #[test] - fn ref_imputation_no_overwrite() { - // If a sample explicitly has the ref allele as an alt with freq 0.7, - // imputation must NOT overwrite it with 1-sum. - let s1 = make_site("A", &[("A", 0.7), ("T", 0.3)]); - let s2 = make_site("A", &[("T", 0.5)]); - let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); - // s1 already has "A" in freqs → should keep 0.7, not overwrite with 1-1.0=0.0 - assert!((psf.freqs1["A"] - 0.7).abs() < 1e-10); - // s2 does NOT have "A" in freqs → should impute 1-0.5=0.5 - assert!((psf.freqs2["A"] - 0.5).abs() < 1e-10); - } +// ── Ref imputation does not overwrite explicit freq ────────────── + +#[test] +fn ref_imputation_no_overwrite() { + // If a sample explicitly has the ref allele as an alt with freq 0.7, + // imputation must NOT overwrite it with 1-sum. + let s1 = make_site("A", &[("A", 0.7), ("T", 0.3)]); + let s2 = make_site("A", &[("T", 0.5)]); + let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); + // s1 already has "A" in freqs → should keep 0.7, not overwrite with 1-1.0=0.0 + assert!((psf.freqs1["A"] - 0.7).abs() < 1e-10); + // s2 does NOT have "A" in freqs → should impute 1-0.5=0.5 + assert!((psf.freqs2["A"] - 0.5).abs() < 1e-10); +} - #[test] - fn ref_imputation_normal_case() { - // Normal VCF case: only alt alleles in freqs, ref should be imputed - let s1 = make_site("A", &[("T", 0.3)]); - let s2 = make_site("A", &[("T", 0.6)]); - let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); - assert!((psf.freqs1["A"] - 0.7).abs() < 1e-10); - assert!((psf.freqs2["A"] - 0.4).abs() < 1e-10); - } +#[test] +fn ref_imputation_normal_case() { + // Normal VCF case: only alt alleles in freqs, ref should be imputed + let s1 = make_site("A", &[("T", 0.3)]); + let s2 = make_site("A", &[("T", 0.6)]); + let psf = get_all_freqs_at_pos(Some(&s1), Some(&s2)); + assert!((psf.freqs1["A"] - 0.7).abs() < 1e-10); + assert!((psf.freqs2["A"] - 0.4).abs() < 1e-10); } diff --git a/src/cli.rs b/src/cli.rs index ebd8567..c85bcd5 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -23,7 +23,12 @@ pub enum InputMode { /// High-performance pairwise genetic distance calculator from allele-frequency data. #[derive(Parser, Debug)] -#[command(name = "fstic", version, about, author = "Paula Ruiz-Rodriguez ")] +#[command( + name = "fstic", + version, + about, + author = "Paula Ruiz-Rodriguez " +)] pub struct Args { /// One or more input VCF files. #[arg(long = "vcf", num_args = 1.., value_name = "VCF_FILES", group = "input")] @@ -97,7 +102,10 @@ impl Args { let files = self.resolve_files(&self.table, &self.table_list)?; Ok((InputMode::Table, files)) } else { - Err("No input files provided. Use --vcf, --vcf-list, --table, or --table-list.".to_string()) + Err( + "No input files provided. Use --vcf, --vcf-list, --table, or --table-list." + .to_string(), + ) } } diff --git a/src/io.rs b/src/io.rs index 181ee9a..5a8869c 100644 --- a/src/io.rs +++ b/src/io.rs @@ -3,9 +3,9 @@ use std::fs::File; use std::io::{BufRead, BufReader, Error}; use std::path::PathBuf; -pub mod vcf; pub mod csv; pub mod fasta; +pub mod vcf; /// Rescales any site whose allele frequencies sum above 1 back to a distribution, /// returning how many sites were touched. diff --git a/src/io/csv.rs b/src/io/csv.rs index 357c910..117de27 100644 --- a/src/io/csv.rs +++ b/src/io/csv.rs @@ -18,7 +18,11 @@ pub fn read_csv_files( let mut all_rows: Vec = Vec::new(); for f in per_file { if let Some(err) = f.open_error { - return Err(format!("Cannot open table file {}: {}", f.path.display(), err)); + return Err(format!( + "Cannot open table file {}: {}", + f.path.display(), + err + )); } if f.rows.is_empty() && f.error_count > 0 { return Err(format!( @@ -43,27 +47,28 @@ pub fn read_csv_files( // combined: the same physical site would land under two different keys. let with_chrom = all_rows.iter().filter(|r| r.chrom.is_some()).count(); if with_chrom != 0 && with_chrom != all_rows.len() { - return Err( - "Some table rows carry a 'chrom' column and others do not. \ + return Err("Some table rows carry a 'chrom' column and others do not. \ Add the column everywhere, or remove it everywhere." - .to_string(), - ); + .to_string()); } - let filtered_rows: Vec = all_rows.into_iter().filter(|row| { - // Validate frequency range - if !row.frequency.is_finite() || !(0.0..=1.0).contains(&row.frequency) { - out_of_range.fetch_add(1, Ordering::Relaxed); - return false; - } - let depth_ok = row.total_dp.is_none_or(|dp| dp >= criteria.min_depth); - let freq_ok = row.frequency >= criteria.min_freq; - let alt_reads_ok = row.alt_dp.is_none_or(|ad| ad >= criteria.min_alt_reads); - let alt_rev_reads_ok = row - .alt_rv - .is_none_or(|arv| arv >= criteria.min_alt_rev_reads); - depth_ok && freq_ok && alt_reads_ok && alt_rev_reads_ok - }).collect(); + let filtered_rows: Vec = all_rows + .into_iter() + .filter(|row| { + // Validate frequency range + if !row.frequency.is_finite() || !(0.0..=1.0).contains(&row.frequency) { + out_of_range.fetch_add(1, Ordering::Relaxed); + return false; + } + let depth_ok = row.total_dp.is_none_or(|dp| dp >= criteria.min_depth); + let freq_ok = row.frequency >= criteria.min_freq; + let alt_reads_ok = row.alt_dp.is_none_or(|ad| ad >= criteria.min_alt_reads); + let alt_rev_reads_ok = row + .alt_rv + .is_none_or(|arv| arv >= criteria.min_alt_rev_reads); + depth_ok && freq_ok && alt_reads_ok && alt_rev_reads_ok + }) + .collect(); let n = out_of_range.load(Ordering::Relaxed); if n > 0 { @@ -81,7 +86,10 @@ pub fn read_csv_files( let gpos = GenomicPos { // Rows either all carry a chrom or none do, so this placeholder is // applied uniformly and cannot split a site in two. - chrom: row.chrom.filter(|c| !c.is_empty()).unwrap_or_else(|| ".".to_string()), + chrom: row + .chrom + .filter(|c| !c.is_empty()) + .unwrap_or_else(|| ".".to_string()), pos: row.position, }; all_positions.insert(gpos.clone()); diff --git a/src/io/fasta.rs b/src/io/fasta.rs index 272b2ee..4b27662 100644 --- a/src/io/fasta.rs +++ b/src/io/fasta.rs @@ -10,7 +10,10 @@ pub type ReferenceGenome = BTreeMap>; /// Stores sequences as `Vec` (1 byte/base) instead of `Vec` (4 bytes/base). pub fn read_reference(path: &str) -> Result { let file = File::open(path).map_err(|e| { - Error::new(ErrorKind::NotFound, format!("Cannot open FASTA file '{}': {}", path, e)) + Error::new( + ErrorKind::NotFound, + format!("Cannot open FASTA file '{}': {}", path, e), + ) })?; let reader = BufReader::new(file); let mut genome = ReferenceGenome::new(); @@ -47,7 +50,11 @@ pub fn read_reference(path: &str) -> Result { )); } if record_open { - flush(&mut genome, std::mem::take(&mut current_name), std::mem::take(&mut current_seq))?; + flush( + &mut genome, + std::mem::take(&mut current_name), + std::mem::take(&mut current_seq), + )?; } current_seq.clear(); current_name = name.to_string(); @@ -56,7 +63,10 @@ pub fn read_reference(path: &str) -> Result { if !record_open { return Err(Error::new( ErrorKind::InvalidData, - format!("Sequence data before the first '>' header in FASTA file '{}'", path), + format!( + "Sequence data before the first '>' header in FASTA file '{}'", + path + ), )); } // Uppercase to handle soft-masked references @@ -68,7 +78,10 @@ pub fn read_reference(path: &str) -> Result { } if genome.is_empty() { - return Err(Error::new(ErrorKind::InvalidData, "No sequences found in FASTA file")); + return Err(Error::new( + ErrorKind::InvalidData, + "No sequences found in FASTA file", + )); } Ok(genome) diff --git a/src/io/vcf.rs b/src/io/vcf.rs index b0ce130..2fdab50 100644 --- a/src/io/vcf.rs +++ b/src/io/vcf.rs @@ -84,7 +84,11 @@ pub fn read_vcf_files( for p in &parsed { if let Some(err) = &p.io_error { - return Err(format!("Error reading VCF file {}: {}", p.path.display(), err)); + return Err(format!( + "Error reading VCF file {}: {}", + p.path.display(), + err + )); } if p.data_lines == 0 { return Err(format!( @@ -157,11 +161,7 @@ struct ParsedVcf { io_error: Option, } -fn parse_and_filter_vcf( - file: &Path, - criteria: &FilterCriteria, - stats: &VcfStats, -) -> ParsedVcf { +fn parse_and_filter_vcf(file: &Path, criteria: &FilterCriteria, stats: &VcfStats) -> ParsedVcf { // Sample ID from filename (one VCF per sample is the expected input model) let sample_id = file .file_stem() @@ -266,9 +266,7 @@ fn parse_and_filter_vcf( let depth_ok = v.total_dp.is_none_or(|dp| dp >= criteria.min_depth); let freq_ok = v.alt_freq >= criteria.min_freq; let alt_reads_ok = v.alt_dp.is_none_or(|ad| ad >= criteria.min_alt_reads); - let alt_rev_reads_ok = v - .alt_rv - .is_none_or(|arv| arv >= criteria.min_alt_rev_reads); + let alt_rev_reads_ok = v.alt_rv.is_none_or(|arv| arv >= criteria.min_alt_rev_reads); depth_ok && freq_ok && alt_reads_ok && alt_rev_reads_ok }) .collect(); @@ -418,7 +416,7 @@ fn parse_vcf_line( alt_allele: fields[4].to_string(), total_dp, alt_dp, - alt_freq, // guaranteed non-None by the ? above + alt_freq, // guaranteed non-None by the ? above alt_rv, }) } diff --git a/src/main.rs b/src/main.rs index 825a083..d7778e5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,11 @@ +mod calculation; mod cli; -mod types; mod io; -mod calculation; +mod types; -use clap::Parser; use crate::cli::{Args, Formula, InputMode}; use crate::types::FilterCriteria; +use clap::Parser; use indicatif::{ProgressBar, ProgressStyle}; use rayon::prelude::*; use std::process::ExitCode; @@ -35,17 +35,25 @@ fn run() -> Result<(), String> { eprintln!("> Minimum Depth (DP): {}", criteria.min_depth); eprintln!("> Minimum Allele Freq (AF): {}", criteria.min_freq); eprintln!("> Minimum Alternate Reads (AD): {}", criteria.min_alt_reads); - eprintln!("> Minimum Alt. Reverse Reads (ADR): {}", criteria.min_alt_rev_reads); + eprintln!( + "> Minimum Alt. Reverse Reads (ADR): {}", + criteria.min_alt_rev_reads + ); eprintln!("------------------------\n"); args.configure_thread_pool(); // Read reference if provided - let reference = args.reference.as_ref().map(|path| { - let path_str = path.to_str().unwrap_or_default(); - eprintln!("Reading reference FASTA..."); - io::fasta::read_reference(path_str) - }).transpose().map_err(|e| format!("Reference error: {}", e))?; + let reference = args + .reference + .as_ref() + .map(|path| { + let path_str = path.to_str().unwrap_or_default(); + eprintln!("Reading reference FASTA..."); + io::fasta::read_reference(path_str) + }) + .transpose() + .map_err(|e| format!("Reference error: {}", e))?; // Read input files eprintln!("Reading {} input files...", files.len()); @@ -72,7 +80,8 @@ fn run() -> Result<(), String> { // still resolves. With several contigs there is nothing to guess from, and // silently reading the wrong contig's base corrupts every distance. let single_contig = genome.len() == 1; - let mut unknown_chroms: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new(); + let mut unknown_chroms: std::collections::BTreeSet<&str> = + std::collections::BTreeSet::new(); let mut out_of_range = 0usize; for gpos in &position_set { @@ -106,7 +115,11 @@ fn run() -> Result<(), String> { Reference alleles were not imputed there.", unknown_chroms.len(), names.join(", "), - if unknown_chroms.len() > names.len() { ", ..." } else { "" } + if unknown_chroms.len() > names.len() { + ", ..." + } else { + "" + } ); } if out_of_range > 0 { @@ -137,7 +150,9 @@ fn run() -> Result<(), String> { } } - let mut conflicting = ref_alleles_by_pos.iter().filter(|(_, alleles)| alleles.len() > 1); + let mut conflicting = ref_alleles_by_pos + .iter() + .filter(|(_, alleles)| alleles.len() > 1); if let Some((gpos, alleles)) = conflicting.next() { let n = 1 + conflicting.count(); let listed: Vec<&str> = alleles.iter().copied().collect(); @@ -154,7 +169,10 @@ fn run() -> Result<(), String> { } if variants_by_sample.is_empty() { - return Err("No samples found after filtering. Check input files and filter thresholds.".to_string()); + return Err( + "No samples found after filtering. Check input files and filter thresholds." + .to_string(), + ); } if position_set.is_empty() { @@ -212,14 +230,51 @@ fn run() -> Result<(), String> { let data2 = variants_by_sample.get(&samples[j]).unwrap(); let dist = match formula { - Formula::Fst => calculation::fst::calculate_fst_for_pair(data1, data2, &all_positions, normalize, num_loci), - Formula::Gst => calculation::gst::calculate_gst_for_pair(data1, data2, &all_positions), - Formula::Nei => calculation::nei::calculate_nei_distance_for_pair(data1, data2, &all_positions), - Formula::Chord => calculation::chord::calculate_chord_distance_for_pair(data1, data2, &all_positions, normalize, num_loci), - Formula::BrayCurtis => calculation::bray_curtis::calculate_bray_curtis_for_pair(data1, data2, &all_positions, normalize, num_loci), - Formula::JostD => calculation::jost_d::calculate_jost_d_for_pair(data1, data2, &all_positions, normalize, num_loci), - Formula::Reynolds => calculation::reynolds::calculate_reynolds_distance_for_pair(data1, data2, &all_positions), - Formula::Rogers => calculation::rogers::calculate_rogers_distance_for_pair(data1, data2, &all_positions, num_loci), + Formula::Fst => calculation::fst::calculate_fst_for_pair( + data1, + data2, + &all_positions, + normalize, + num_loci, + ), + Formula::Gst => { + calculation::gst::calculate_gst_for_pair(data1, data2, &all_positions) + } + Formula::Nei => { + calculation::nei::calculate_nei_distance_for_pair(data1, data2, &all_positions) + } + Formula::Chord => calculation::chord::calculate_chord_distance_for_pair( + data1, + data2, + &all_positions, + normalize, + num_loci, + ), + Formula::BrayCurtis => calculation::bray_curtis::calculate_bray_curtis_for_pair( + data1, + data2, + &all_positions, + normalize, + num_loci, + ), + Formula::JostD => calculation::jost_d::calculate_jost_d_for_pair( + data1, + data2, + &all_positions, + normalize, + num_loci, + ), + Formula::Reynolds => calculation::reynolds::calculate_reynolds_distance_for_pair( + data1, + data2, + &all_positions, + ), + Formula::Rogers => calculation::rogers::calculate_rogers_distance_for_pair( + data1, + data2, + &all_positions, + num_loci, + ), }; pb.inc(1); ((i, j), dist) @@ -244,7 +299,12 @@ fn run() -> Result<(), String> { > Output: {}\n\ > Time: {:.2}s\n\ ---------------", - samples.len(), num_loci, sample_pairs.len(), formula, output_path_str, elapsed.as_secs_f64() + samples.len(), + num_loci, + sample_pairs.len(), + formula, + output_path_str, + elapsed.as_secs_f64() ); Ok(()) diff --git a/tests/integration.rs b/tests/integration.rs index 166a084..77a7980 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -15,8 +15,14 @@ fn write_vcf(dir: &Path, name: &str, lines: &[&str]) { /// instead of a substring is the difference between a real check and one that the /// zero on the diagonal satisfies by accident. fn off_diagonal(content: &str, sep: char) -> f64 { - let line = content.lines().nth(1).expect("matrix needs a first data row"); - let cell = line.split(sep).nth(2).expect("matrix needs a second column"); + let line = content + .lines() + .nth(1) + .expect("matrix needs a first data row"); + let cell = line + .split(sep) + .nth(2) + .expect("matrix needs a second column"); cell.trim() .parse() .unwrap_or_else(|_| panic!("cell {:?} is not a number", cell)) @@ -26,19 +32,28 @@ fn off_diagonal(content: &str, sep: char) -> f64 { #[test] fn identical_samples_zero_distance() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "sampleA", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50.0%", - "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30.0%", - ]); + write_vcf( + dir.path(), + "sampleA", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50.0%", + "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30.0%", + ], + ); - write_vcf(dir.path(), "sampleB", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50.0%", - "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30.0%", - ]); + write_vcf( + dir.path(), + "sampleB", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50.0%", + "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30.0%", + ], + ); let out = dir.path().join("out.csv"); @@ -49,11 +64,16 @@ fn identical_samples_zero_distance() { dir.path().join("sampleB.vcf").to_str().unwrap(), "-o", out.to_str().unwrap(), - "--formula", "fst", - "--min-depth", "1", - "--min-af", "0.01", - "--min-alt-reads", "1", - "--min-alt-rev-reads", "0", + "--formula", + "fst", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -69,17 +89,26 @@ fn identical_samples_zero_distance() { #[test] fn different_samples_positive_fst() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "pop1", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:90:90.0%", - ]); + write_vcf( + dir.path(), + "pop1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:90:90.0%", + ], + ); - write_vcf(dir.path(), "pop2", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:10:10.0%", - ]); + write_vcf( + dir.path(), + "pop2", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:10:10.0%", + ], + ); let out = dir.path().join("out.tsv"); let status = fstic_bin() @@ -89,11 +118,16 @@ fn different_samples_positive_fst() { dir.path().join("pop2.vcf").to_str().unwrap(), "-o", out.to_str().unwrap(), - "--formula", "fst", - "--min-depth", "1", - "--min-af", "0.01", - "--min-alt-reads", "1", - "--min-alt-rev-reads", "0", + "--formula", + "fst", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -113,18 +147,27 @@ fn different_samples_positive_fst() { #[test] fn freq_as_proportion() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; // 0.5 = 50%, NOT 0.5% - write_vcf(dir.path(), "propA", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:0.5", - ]); + write_vcf( + dir.path(), + "propA", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:0.5", + ], + ); - write_vcf(dir.path(), "propB", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", - ]); + write_vcf( + dir.path(), + "propB", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", + ], + ); let out = dir.path().join("out.csv"); let status = fstic_bin() @@ -134,11 +177,16 @@ fn freq_as_proportion() { dir.path().join("propB.vcf").to_str().unwrap(), "-o", out.to_str().unwrap(), - "--formula", "fst", - "--min-depth", "1", - "--min-af", "0.01", - "--min-alt-reads", "1", - "--min-alt-rev-reads", "0", + "--formula", + "fst", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -149,23 +197,36 @@ fn freq_as_proportion() { let lines: Vec<&str> = content.lines().collect(); let vals: Vec<&str> = lines[1].split(',').collect(); let dist: f64 = vals[2].parse().unwrap(); - assert!(dist.abs() < 1e-6, "Same freq (0.5 vs 50%) should give 0 distance, got {}", dist); + assert!( + dist.abs() < 1e-6, + "Same freq (0.5 vs 50%) should give 0 distance, got {}", + dist + ); } /// VCF mode should NOT require --reference. #[test] fn vcf_no_reference_required() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", - ]); - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", - ]); + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", + ], + ); + write_vcf( + dir.path(), + "s2", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", + ], + ); let out = dir.path().join("out.csv"); // No --reference flag @@ -174,11 +235,16 @@ fn vcf_no_reference_required() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", - "--min-af", "0.01", - "--min-alt-reads", "1", - "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -190,17 +256,26 @@ fn vcf_no_reference_required() { #[test] fn indels_skipped() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; // Only indels, no SNPs → should fail with "no polymorphic sites" - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tAT\tA\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", - ]); - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t100\t.\tAT\tA\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30%", - ]); + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tAT\tA\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", + ], + ); + write_vcf( + dir.path(), + "s2", + &[ + header, + "chr1\t100\t.\tAT\tA\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30%", + ], + ); let out = dir.path().join("out.csv"); let status = fstic_bin() @@ -208,9 +283,16 @@ fn indels_skipped() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -223,18 +305,27 @@ fn indels_skipped() { #[test] fn non_variant_and_star_skipped() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tA\t.\t.\t.\t.\tGT:DP:AD:FREQ\t0/0:100:0:0%", // no-variant - "chr1\t200\t.\tA\t*\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", // upstream del - "chr1\t300\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", // real SNP - ]); - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t300\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30%", - ]); + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tA\t.\t.\t.\t.\tGT:DP:AD:FREQ\t0/0:100:0:0%", // no-variant + "chr1\t200\t.\tA\t*\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", // upstream del + "chr1\t300\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", // real SNP + ], + ); + write_vcf( + dir.path(), + "s2", + &[ + header, + "chr1\t300\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:30:30%", + ], + ); let out = dir.path().join("out.csv"); let res = fstic_bin() @@ -242,10 +333,18 @@ fn non_variant_and_star_skipped() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--formula", "bray-curtis", - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--formula", + "bray-curtis", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .output() .unwrap(); @@ -257,7 +356,11 @@ fn non_variant_and_star_skipped() { assert!(err.contains("1 polymorphic sites"), "got: {}", err); // 0.5 against 0.3 over one locus let content = fs::read_to_string(&out).unwrap(); - assert!((off_diagonal(&content, ',') - 0.2).abs() < 1e-12, "matrix was:\n{}", content); + assert!( + (off_diagonal(&content, ',') - 0.2).abs() < 1e-12, + "matrix was:\n{}", + content + ); } /// Nei and Reynolds return infinity for a fixed difference, which has to reach the @@ -265,10 +368,25 @@ fn non_variant_and_star_skipped() { #[test] fn non_finite_distance_is_written_as_na() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "fixA", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t1/1:100:100%"]); - write_vcf(dir.path(), "fixB", &[header, "chr1\t100\t.\tA\tG\t.\t.\t.\tGT:DP:FREQ\t1/1:100:100%"]); + write_vcf( + dir.path(), + "fixA", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t1/1:100:100%", + ], + ); + write_vcf( + dir.path(), + "fixB", + &[ + header, + "chr1\t100\t.\tA\tG\t.\t.\t.\tGT:DP:FREQ\t1/1:100:100%", + ], + ); let out = dir.path().join("out.csv"); let status = fstic_bin() @@ -276,10 +394,18 @@ fn non_finite_distance_is_written_as_na() { "--vcf", dir.path().join("fixA.vcf").to_str().unwrap(), dir.path().join("fixB.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--formula", "nei", - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--formula", + "nei", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -295,10 +421,25 @@ fn non_finite_distance_is_written_as_na() { #[test] fn sample_names_containing_the_separator_are_quoted() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "with,comma", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%"]); - write_vcf(dir.path(), "plain", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:10%"]); + write_vcf( + dir.path(), + "with,comma", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%", + ], + ); + write_vcf( + dir.path(), + "plain", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:10%", + ], + ); let out = dir.path().join("out.csv"); let status = fstic_bin() @@ -306,16 +447,27 @@ fn sample_names_containing_the_separator_are_quoted() { "--vcf", dir.path().join("with,comma.vcf").to_str().unwrap(), dir.path().join("plain.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); assert!(status.success()); let content = fs::read_to_string(&out).unwrap(); - assert!(content.contains("\"with,comma\""), "name was not quoted:\n{}", content); + assert!( + content.contains("\"with,comma\""), + "name was not quoted:\n{}", + content + ); // Header plus two rows, each with 3 fields once quoting is honoured for line in content.lines() { let fields = line.matches(',').count() - line.matches("\"with,comma\"").count(); @@ -332,18 +484,27 @@ fn sample_names_containing_the_separator_are_quoted() { #[test] fn freq_from_ad_dp() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; // AD=20,80 means 80 alt reads out of 100, i.e. 0.8 - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD\t0/1:100:20,80", - ]); + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD\t0/1:100:20,80", + ], + ); // Same frequency, stated outright - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:80%", - ]); + write_vcf( + dir.path(), + "s2", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:80%", + ], + ); let out = dir.path().join("out.csv"); let status = fstic_bin() @@ -351,10 +512,18 @@ fn freq_from_ad_dp() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--formula", "bray-curtis", - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--formula", + "bray-curtis", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -377,13 +546,20 @@ fn run_table(dir: &Path, body: &str, extra: &[&str]) -> (std::process::Output, s let reference = write_ref(dir); let out = dir.join("out.csv"); let mut args: Vec = vec![ - "--table".into(), table.to_str().unwrap().into(), - "-r".into(), reference.to_str().unwrap().into(), - "-o".into(), out.to_str().unwrap().into(), - "--min-depth".into(), "1".into(), - "--min-af".into(), "0.01".into(), - "--min-alt-reads".into(), "1".into(), - "--min-alt-rev-reads".into(), "0".into(), + "--table".into(), + table.to_str().unwrap().into(), + "-r".into(), + reference.to_str().unwrap().into(), + "-o".into(), + out.to_str().unwrap().into(), + "--min-depth".into(), + "1".into(), + "--min-af".into(), + "0.01".into(), + "--min-alt-reads".into(), + "1".into(), + "--min-alt-rev-reads".into(), + "0".into(), ]; args.extend(extra.iter().map(|s| s.to_string())); (fstic_bin().args(&args).output().unwrap(), out) @@ -393,9 +569,24 @@ fn run_table(dir: &Path, body: &str, extra: &[&str]) -> (std::process::Output, s #[test] fn table_matches_vcf_on_equivalent_data() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "sA", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:50%"]); - write_vcf(dir.path(), "sB", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:80%"]); + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + write_vcf( + dir.path(), + "sA", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:50%", + ], + ); + write_vcf( + dir.path(), + "sB", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:80%", + ], + ); let vcf_out = dir.path().join("vcf.csv"); let status = fstic_bin() @@ -403,10 +594,18 @@ fn table_matches_vcf_on_equivalent_data() { "--vcf", dir.path().join("sA.vcf").to_str().unwrap(), dir.path().join("sB.vcf").to_str().unwrap(), - "-o", vcf_out.to_str().unwrap(), - "--formula", "chord", - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + vcf_out.to_str().unwrap(), + "--formula", + "chord", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -419,11 +618,20 @@ fn table_matches_vcf_on_equivalent_data() { sB,chr1,100,A,T,0.8\n", &["--formula", "chord"], ); - assert!(res.status.success(), "{}", String::from_utf8_lossy(&res.stderr)); + assert!( + res.status.success(), + "{}", + String::from_utf8_lossy(&res.stderr) + ); let from_vcf = off_diagonal(&fs::read_to_string(&vcf_out).unwrap(), ','); let from_table = off_diagonal(&fs::read_to_string(&table_out).unwrap(), ','); - assert!((from_vcf - from_table).abs() < 1e-12, "{} vs {}", from_vcf, from_table); + assert!( + (from_vcf - from_table).abs() < 1e-12, + "{} vs {}", + from_vcf, + from_table + ); } /// The README promises case-insensitive column names. @@ -437,7 +645,11 @@ fn table_headers_are_case_insensitive() { sB,100,A,T,0.8\n", &["--formula", "bray-curtis"], ); - assert!(res.status.success(), "{}", String::from_utf8_lossy(&res.stderr)); + assert!( + res.status.success(), + "{}", + String::from_utf8_lossy(&res.stderr) + ); assert!((off_diagonal(&fs::read_to_string(&out).unwrap(), ',') - 0.3).abs() < 1e-12); } @@ -452,7 +664,11 @@ fn table_accepts_percentage_frequencies() { sB,100,A,T,80%\n", &["--formula", "bray-curtis"], ); - assert!(res.status.success(), "{}", String::from_utf8_lossy(&res.stderr)); + assert!( + res.status.success(), + "{}", + String::from_utf8_lossy(&res.stderr) + ); assert!((off_diagonal(&fs::read_to_string(&out).unwrap(), ',') - 0.3).abs() < 1e-12); } @@ -482,17 +698,35 @@ fn table_mixed_chrom_column_is_rejected() { let reference = write_ref(dir.path()); let a = dir.path().join("a.csv"); let b = dir.path().join("b.csv"); - fs::write(&a, "sample,chrom,position,ref_allele,sequence,frequency\nsA,chr1,100,A,T,0.5\n").unwrap(); - fs::write(&b, "sample,position,ref_allele,sequence,frequency\nsB,100,A,T,0.8\n").unwrap(); + fs::write( + &a, + "sample,chrom,position,ref_allele,sequence,frequency\nsA,chr1,100,A,T,0.5\n", + ) + .unwrap(); + fs::write( + &b, + "sample,position,ref_allele,sequence,frequency\nsB,100,A,T,0.8\n", + ) + .unwrap(); let out = dir.path().join("out.csv"); let res = fstic_bin() .args([ - "--table", a.to_str().unwrap(), b.to_str().unwrap(), - "-r", reference.to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "--table", + a.to_str().unwrap(), + b.to_str().unwrap(), + "-r", + reference.to_str().unwrap(), + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .output() .unwrap(); @@ -507,11 +741,33 @@ fn table_mixed_chrom_column_is_rejected() { #[test] fn sample_with_no_surviving_variants_keeps_its_row() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "keep1", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%"]); - write_vcf(dir.path(), "keep2", &[header, "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%"]); - write_vcf(dir.path(), "quiet", &[header, "chr1\t300\t.\tT\tC\t.\t.\t.\tGT:DP:FREQ\t0/1:100:10%"]); + write_vcf( + dir.path(), + "keep1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%", + ], + ); + write_vcf( + dir.path(), + "keep2", + &[ + header, + "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%", + ], + ); + write_vcf( + dir.path(), + "quiet", + &[ + header, + "chr1\t300\t.\tT\tC\t.\t.\t.\tGT:DP:FREQ\t0/1:100:10%", + ], + ); let out = dir.path().join("out.csv"); let res = fstic_bin() @@ -520,20 +776,41 @@ fn sample_with_no_surviving_variants_keeps_its_row() { dir.path().join("keep1.vcf").to_str().unwrap(), dir.path().join("keep2.vcf").to_str().unwrap(), dir.path().join("quiet.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--formula", "bray-curtis", - "--min-depth", "1", "--min-af", "0.5", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--formula", + "bray-curtis", + "--min-depth", + "1", + "--min-af", + "0.5", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .output() .unwrap(); assert!(res.status.success()); let content = fs::read_to_string(&out).unwrap(); - assert_eq!(content.lines().count(), 4, "3 samples plus header:\n{}", content); - assert!(content.lines().any(|l| l.starts_with("quiet,")), "missing row:\n{}", content); + assert_eq!( + content.lines().count(), + 4, + "3 samples plus header:\n{}", + content + ); + assert!( + content.lines().any(|l| l.starts_with("quiet,")), + "missing row:\n{}", + content + ); let err = String::from_utf8_lossy(&res.stderr); - assert!(err.contains("no variants left after filtering"), "got: {}", err); + assert!( + err.contains("no variants left after filtering"), + "got: {}", + err + ); } /// Sample names come from the file stem, so equal basenames would silently merge @@ -541,13 +818,28 @@ fn sample_with_no_surviving_variants_keeps_its_row() { #[test] fn duplicate_sample_names_are_rejected() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; let (a, b) = (dir.path().join("a"), dir.path().join("b")); fs::create_dir_all(&a).unwrap(); fs::create_dir_all(&b).unwrap(); - write_vcf(&a, "s", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%"]); - write_vcf(&b, "s", &[header, "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:10%"]); + write_vcf( + &a, + "s", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:90%", + ], + ); + write_vcf( + &b, + "s", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:10%", + ], + ); let out = dir.path().join("out.csv"); let res = fstic_bin() @@ -555,9 +847,16 @@ fn duplicate_sample_names_are_rejected() { "--vcf", a.join("s.vcf").to_str().unwrap(), b.join("s.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .output() .unwrap(); @@ -572,17 +871,23 @@ fn duplicate_sample_names_are_rejected() { #[test] fn freq_above_one_from_ad_dp_is_dropped() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD\t0/1:10:15", // AD > DP, unusable - "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD\t0/1:100:50", // fine - ]); - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD\t0/1:100:50", - ]); + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD\t0/1:10:15", // AD > DP, unusable + "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD\t0/1:100:50", // fine + ], + ); + write_vcf( + dir.path(), + "s2", + &[header, "chr1\t200\t.\tC\tG\t.\t.\t.\tGT:DP:AD\t0/1:100:50"], + ); let out = dir.path().join("out.csv"); let res = fstic_bin() @@ -590,16 +895,27 @@ fn freq_above_one_from_ad_dp_is_dropped() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .output() .unwrap(); assert!(res.status.success()); let err = String::from_utf8_lossy(&res.stderr); - assert!(err.contains("outside [0,1]"), "the drop must be reported, got: {}", err); + assert!( + err.contains("outside [0,1]"), + "the drop must be reported, got: {}", + err + ); // Only chr1:200 survives, and both samples agree there assert!(err.contains("1 polymorphic sites"), "got: {}", err); assert_eq!(off_diagonal(&fs::read_to_string(&out).unwrap(), ','), 0.0); @@ -609,16 +925,25 @@ fn freq_above_one_from_ad_dp_is_dropped() { #[test] fn unparseable_ad_is_reported() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:.,.:90%", - ]); - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:90,10:10%", - ]); + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:.,.:90%", + ], + ); + write_vcf( + dir.path(), + "s2", + &[ + header, + "chr1\t100\t.\tA\tT\t.\t.\t.\tGT:DP:AD:FREQ\t0/1:100:90,10:10%", + ], + ); let out = dir.path().join("out.csv"); let res = fstic_bin() @@ -626,9 +951,16 @@ fn unparseable_ad_is_reported() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "50", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "50", + "--min-alt-rev-reads", + "0", ]) .output() .unwrap(); @@ -646,7 +978,8 @@ fn unparseable_ad_is_reported() { #[test] fn output_is_independent_of_worker_count() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; // Enough loci, at irregular frequencies, for the summation order to show up. let mut a = vec![header.to_string()]; @@ -654,8 +987,14 @@ fn output_is_independent_of_worker_count() { for pos in 1..4000 { let fa = 3.0 + (pos as f64 * 7.3) % 91.0; let fb = 2.0 + (pos as f64 * 11.7) % 93.0; - a.push(format!("chr1\t{}\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:{:.6}%", pos, fa)); - b.push(format!("chr1\t{}\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:{:.6}%", pos, fb)); + a.push(format!( + "chr1\t{}\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:{:.6}%", + pos, fa + )); + b.push(format!( + "chr1\t{}\t.\tA\tT\t.\t.\t.\tGT:DP:FREQ\t0/1:100:{:.6}%", + pos, fb + )); } let a_ref: Vec<&str> = a.iter().map(|s| s.as_str()).collect(); let b_ref: Vec<&str> = b.iter().map(|s| s.as_str()).collect(); @@ -669,11 +1008,20 @@ fn output_is_independent_of_worker_count() { "--vcf", dir.path().join("wa.vcf").to_str().unwrap(), dir.path().join("wb.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), - "--formula", "fst", - "--workers", workers, - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out.to_str().unwrap(), + "--formula", + "fst", + "--workers", + workers, + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -683,7 +1031,12 @@ fn output_is_independent_of_worker_count() { let one = run("1", "w1.csv"); for (workers, name) in [("2", "w2.csv"), ("3", "w3.csv"), ("8", "w8.csv")] { - assert_eq!(one, run(workers, name), "--workers {} changed the output", workers); + assert_eq!( + one, + run(workers, name), + "--workers {} changed the output", + workers + ); } } @@ -691,18 +1044,27 @@ fn output_is_independent_of_worker_count() { #[test] fn pass_only_filter() { let dir = tempfile::tempdir().unwrap(); - let header = "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; - - write_vcf(dir.path(), "s1", &[ - header, - "chr1\t100\t.\tA\tT\t.\tLowQual\t.\tGT:DP:AD:FREQ\t0/1:100:90:90%", // filtered - "chr1\t200\t.\tC\tG\t.\tPASS\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", // pass - ]); - write_vcf(dir.path(), "s2", &[ - header, - "chr1\t100\t.\tA\tT\t.\tPASS\t.\tGT:DP:AD:FREQ\t0/1:100:10:10%", - "chr1\t200\t.\tC\tG\t.\tPASS\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", - ]); + let header = + "##fileformat=VCFv4.2\n#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tsample"; + + write_vcf( + dir.path(), + "s1", + &[ + header, + "chr1\t100\t.\tA\tT\t.\tLowQual\t.\tGT:DP:AD:FREQ\t0/1:100:90:90%", // filtered + "chr1\t200\t.\tC\tG\t.\tPASS\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", // pass + ], + ); + write_vcf( + dir.path(), + "s2", + &[ + header, + "chr1\t100\t.\tA\tT\t.\tPASS\t.\tGT:DP:AD:FREQ\t0/1:100:10:10%", + "chr1\t200\t.\tC\tG\t.\tPASS\t.\tGT:DP:AD:FREQ\t0/1:100:50:50%", + ], + ); let out = dir.path().join("out.csv"); let status = fstic_bin() @@ -710,10 +1072,17 @@ fn pass_only_filter() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out.to_str().unwrap(), + "-o", + out.to_str().unwrap(), "--pass-only", - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -727,9 +1096,16 @@ fn pass_only_filter() { "--vcf", dir.path().join("s1.vcf").to_str().unwrap(), dir.path().join("s2.vcf").to_str().unwrap(), - "-o", out_no_filter.to_str().unwrap(), - "--min-depth", "1", "--min-af", "0.01", - "--min-alt-reads", "1", "--min-alt-rev-reads", "0", + "-o", + out_no_filter.to_str().unwrap(), + "--min-depth", + "1", + "--min-af", + "0.01", + "--min-alt-reads", + "1", + "--min-alt-rev-reads", + "0", ]) .status() .unwrap(); @@ -745,5 +1121,10 @@ fn pass_only_filter() { }; let d_filt = get_dist(&content_filt); let d_nofilt = get_dist(&content_nofilt); - assert!(d_filt < d_nofilt, "--pass-only should reduce distance (filtered {} vs unfiltered {})", d_filt, d_nofilt); + assert!( + d_filt < d_nofilt, + "--pass-only should reduce distance (filtered {} vs unfiltered {})", + d_filt, + d_nofilt + ); }