diff --git a/.github/scripts/release.sh b/.github/scripts/release.sh new file mode 100755 index 0000000..d7a1570 --- /dev/null +++ b/.github/scripts/release.sh @@ -0,0 +1,108 @@ +#!/usr/bin/env bash +# Release checks and packages for HarmonizePy. +# +# release.sh version print the version, after checking pyproject.toml, __init__.py, and CITATION.cff agree +# release.sh notes [TAG] print the CHANGELOG.md section of the version (TAG must be vVERSION) +# release.sh package OUTPUT_DIR build the wheel and sdist, check them, smoke-test the wheel, copy both to OUTPUT_DIR +# +# The sdist must hold only files git tracks, and the wheel is installed into a fresh environment outside the +# checkout and run there. Work directories are made under RUNNER_TEMP (or /var/tmp) and left in place. + +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")/../.." + +die() { + printf 'error: %s\n' "$*" >&2 + exit 1 +} + +version=$(sed -n 's/^version = "\([^"]*\)"$/\1/p' pyproject.toml) +[[ "$version" =~ ^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || + die "pyproject.toml must declare one major.minor.patch version" +init_version=$(sed -n 's/^__version__ = "\([^"]*\)"$/\1/p' src/harmonizepy/__init__.py) +[[ "$init_version" == "$version" ]] || die "__init__.py has version '$init_version', pyproject.toml '$version'" +cff_version=$(sed -n 's/^version: \(.*\)$/\1/p' CITATION.cff) +[[ "$cff_version" == "$version" ]] || die "CITATION.cff has version '$cff_version', pyproject.toml '$version'" + +notes() { + awk -v version="$version" ' + /^## / { + if (found) exit + found = ($2 == "[" version "]") + next + } + found { + if ($0 ~ /[^[:space:]]/) nonempty = 1 + if (nonempty) print + } + END { if (!found || !nonempty) exit 1 } + ' CHANGELOG.md || die "CHANGELOG.md needs a nonempty [$version] section" +} + +package() { + local output="$1" work dist wheel sdist untracked name="harmonizepy-$version" + work=$(mktemp -d "${RUNNER_TEMP:-/var/tmp}/harmonizepy-release.XXXXXX") + dist="$work/dist" + uv build --out-dir "$dist" > "$work/build.log" 2>&1 || { cat "$work/build.log" >&2; die "uv build failed"; } + wheel="$dist/$name-py3-none-any.whl" + sdist="$dist/$name.tar.gz" + [[ -s "$wheel" && -s "$sdist" ]] || die "expected $name-py3-none-any.whl and $name.tar.gz, found: $(ls "$dist")" + [[ "$(find "$dist" -maxdepth 1 -type f \( -name '*.whl' -o -name '*.tar.gz' \) | wc -l)" -eq 2 ]] || + die "expected one wheel and one sdist in the build output: $(ls "$dist")" + + tar -tzf "$sdist" | sed -n "s,^$name/,,p" | grep -v -e '/$' -e '^PKG-INFO$' | LC_ALL=C sort > "$work/sdist-files" + git ls-files | LC_ALL=C sort > "$work/tracked-files" + untracked=$(LC_ALL=C comm -23 "$work/sdist-files" "$work/tracked-files") + [[ -z "$untracked" ]] || die "the sdist holds files git does not track: $untracked" + + uv venv --quiet --python 3.12 "$work/venv" + uv pip install --quiet --python "$work/venv/bin/python" "$wheel" + ( + cd "$work" + export PATH="$work/venv/bin:/usr/bin:/bin" + [[ "$(harmonizepy --version)" == "harmonizepy $version" ]] || die "--version is not 'harmonizepy $version'" + python - <<'PY' +import numpy as np +import pandas as pd + +import harmonizepy + +rng = np.random.default_rng(0) +batch = np.repeat([1, 2, 3], 4) +values = rng.normal(20, 1, (30, 1)) + rng.normal(0, 0.3, (30, 12)) + np.array([0.0, 1.0, -1.0])[batch - 1] +values[:2, batch == 3] = np.nan +samples = [f"s{i}" for i in range(12)] +data = pd.DataFrame(values, index=[f"f{i}" for i in range(30)], columns=samples) +data.to_csv("data.tsv", sep="\t") +pd.DataFrame({"ID": samples, "sample": range(1, 13), "batch": batch}).to_csv("batch.csv", index=False) +for algorithm, mode in (("ComBat", 1), ("ComBat", 3), ("limma", 1)): + out, report = harmonizepy.harmonize(data, "batch.csv", algorithm=algorithm, combat_mode=mode, return_report=True) + assert out.shape == data.shape and report["status"].eq("corrected").all(), (algorithm, mode) + assert out.iloc[:2, 8:].isna().all().all() and np.isfinite(out.iloc[2:]).all().all() +PY + harmonizepy data.tsv batch.csv -o corrected.tsv --report report.tsv --no-log -q + [[ "$(wc -l < corrected.tsv)" -eq 31 && "$(wc -l < report.tsv)" -eq 31 ]] || die "the CLI run wrote the wrong number of rows" + ) + mkdir -p "$output" + cp "$wheel" "$sdist" "$output/" + printf 'tested %s\n' "$output/$(basename "$wheel")" "$output/$(basename "$sdist")" +} + +case "${1:-}" in + version) + printf '%s\n' "$version" + ;; + notes) + tag="${2:-v$version}" + [[ "$tag" == "v$version" ]] || die "tag $tag does not match version v$version" + notes + ;; + package) + [[ $# -eq 2 ]] || die "usage: release.sh package OUTPUT_DIR" + package "$2" + ;; + *) + printf 'usage: release.sh version | notes [TAG] | package OUTPUT_DIR\n' >&2 + exit 2 + ;; +esac diff --git a/.github/scripts/wiki_check.py b/.github/scripts/wiki_check.py index 0b4fd5d..6a01a0a 100755 --- a/.github/scripts/wiki_check.py +++ b/.github/scripts/wiki_check.py @@ -16,6 +16,9 @@ _LINK_TITLE = re.compile(r"""\s+(?:"[^"]*"|'[^']*'|\([^)]*\))\s*$""") _INLINE_CODE = re.compile(r"`+[^`\n]*`+") _FENCE = re.compile(r"^( {0,3})(`{3,}|~{3,})") +_ASSET_DIR = "assets" +_ASSET_SUFFIXES = (".png",) +_ASSET_REFERENCE = re.compile(r"""(?:src|srcset)\s*=\s*["']([^"']+)["']|!\[[^]\n]*\]\(([^)\s]+)""") def _blank(text: str) -> str: @@ -87,6 +90,26 @@ def _is_external(target: str) -> bool: ) or target.startswith("#") +def _validate_assets(asset_dir: Path, assets: set[str]) -> list[str]: + """Check the image folder and record its files as ``assets/NAME`` references.""" + + errors: list[str] = [] + for entry in sorted(asset_dir.iterdir(), key=lambda path: path.name.casefold()): + relative = f"{asset_dir}/{entry.name}" + if entry.is_symlink() or not entry.is_file(): + errors.append(f"{_ASSET_DIR}/ entries must be regular files: {relative}") + continue + if not entry.name.casefold().endswith(_ASSET_SUFFIXES): + errors.append(f"{_ASSET_DIR}/ permits PNG images only: {relative}") + continue + if _PORTABLE_FILENAME_CHARS.search(entry.name): + errors.append(f"image filename contains a non-portable character: {relative}") + if entry.stat().st_size == 0: + errors.append(f"image is empty: {relative}") + assets.add(f"{_ASSET_DIR}/{entry.name}") + return errors + + def validate(wiki_dir: Path) -> list[str]: """Return validation errors for ``wiki_dir``; an empty list means valid.""" @@ -98,10 +121,17 @@ def validate(wiki_dir: Path) -> list[str]: pages: list[Path] = [] aliases: dict[str, Path] = {} + assets: set[str] = set() + for entry in entries: relative = f"{wiki_dir}/{entry.name}" + if entry.name == _ASSET_DIR and entry.is_dir() and not entry.is_symlink(): + errors.extend(_validate_assets(entry, assets)) + continue if entry.is_symlink() or not entry.is_file(): - errors.append(f"wiki entries must be regular top-level files: {relative}") + errors.append( + f"wiki entries must be regular top-level files or the {_ASSET_DIR}/ folder: {relative}" + ) continue if not entry.name.endswith(".md"): errors.append(f"wiki source currently permits Markdown pages only: {relative}") @@ -134,6 +164,14 @@ def validate(wiki_dir: Path) -> list[str]: continue visible_text = _without_code(text) + for match in _ASSET_REFERENCE.finditer(visible_text): + reference = (match.group(1) or match.group(2)).strip() + if _is_external(reference) or not reference.startswith(f"{_ASSET_DIR}/"): + continue + if reference not in assets: + line = _line_number(text, match.start()) + errors.append(f"{page}:{line} references a missing image: {reference}") + for match in _WIKI_LINK.finditer(visible_text): specification = match.group(1).strip() page_target = specification.split("|", 1)[0].strip() diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab46e39..9146ddb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,6 +40,33 @@ jobs: - name: Mypy run: uv run mypy src/ + package: + name: Package + runs-on: ubuntu-24.04 + timeout-minutes: 15 + + steps: + - name: Check out repository + uses: actions/checkout@v7.0.1 + + - name: Install uv + uses: astral-sh/setup-uv@v10.3.0 + with: + enable-cache: true + cache-suffix: package + + - name: Build, check, and smoke-test the wheel and sdist + run: bash .github/scripts/release.sh package "$RUNNER_TEMP/dist" + + # The release workflow publishes these files from main's CI run on the tagged commit. + - name: Keep the tested packages + uses: actions/upload-artifact@v7.0.2 + with: + name: release-dist + path: ${{ runner.temp }}/dist/* + if-no-files-found: error + retention-days: 90 + test: name: Test ${{ matrix.name }} runs-on: ${{ matrix.os }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..2b6b102 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,161 @@ +# Publishes a GitHub release for a vX.Y.Z tag, in two steps; the first failure stops it. +# +# - gate: the tag names the version in pyproject.toml, __init__.py, and CITATION.cff, CHANGELOG.md has its section, +# the tagged commit is main's head, and main's CI on that commit has passed. Nothing is rebuilt: a tag pushed +# before that CI run finishes fails, and the release is re-run once it has passed. CI keeps the packages for +# 90 days; after that, the release needs a new CI run on main. +# - publish: the wheel and sdist that CI built and smoke-tested, with checksums and the changelog section as notes, +# as a draft release first, so a failed upload or attestation can be re-run without a half-published release; +# attestations; and only then the public release. +# +# Started by hand on main, it rehearses the gate for main's version and publishes nothing. +# It does not upload to a package index. +name: release + +on: + push: + tags: ['v*'] + workflow_dispatch: + +permissions: {} + +concurrency: + group: release-${{ github.ref }} + cancel-in-progress: false + +jobs: + gate: + name: Release gate + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + actions: read + outputs: + tag: ${{ steps.tag.outputs.tag }} + version: ${{ steps.tag.outputs.version }} + run: ${{ steps.ci.outputs.run }} + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - name: Check out the tagged source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check the tag, version, and notes + id: tag + run: | + set -euo pipefail + version=$(bash .github/scripts/release.sh version) + if [[ "$GITHUB_EVENT_NAME" == workflow_dispatch ]]; then + test "$GITHUB_REF" = refs/heads/main || { echo "a rehearsal runs on main, not $GITHUB_REF" >&2; exit 1; } + tag="v$version" + else + tag="$GITHUB_REF_NAME" + [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "tag must be vX.Y.Z: $tag" >&2; exit 1; } + test "$tag" = "v$version" || { echo "tag $tag does not match version $version" >&2; exit 1; } + fi + bash .github/scripts/release.sh notes "$tag" > /dev/null + printf 'tag=%s\nversion=%s\n' "$tag" "$version" >> "$GITHUB_OUTPUT" + + - name: Check the commit is main's head + env: + TAG: ${{ steps.tag.outputs.tag }} + run: | + set -euo pipefail + main=$(gh api "repos/$GH_REPO/commits/main" --jq .sha) + test "$GITHUB_SHA" = "$main" || { echo "$TAG at $GITHUB_SHA is not main's head ($main)" >&2; exit 1; } + + - name: Find main's passed CI run on the commit + id: ci + run: | + set -euo pipefail + run=$(gh run list --workflow ci.yml --branch main --commit "$GITHUB_SHA" --limit 20 \ + --json databaseId,event,status,conclusion \ + --jq '[.[] | select(.event == "push")][0] // empty | [.databaseId, .status, .conclusion] | @tsv') + [[ -n "$run" ]] || { echo "no CI run on main for $GITHUB_SHA" >&2; exit 1; } + IFS=$'\t' read -r id status conclusion <<< "$run" + [[ "$status" == completed ]] || { echo "CI run $id on main has not finished; re-run the release after it passes" >&2; exit 1; } + [[ "$conclusion" == success ]] || { echo "CI run $id on main concluded $conclusion" >&2; exit 1; } + printf 'run=%s\n' "$id" >> "$GITHUB_OUTPUT" + + publish: + name: Publish release + needs: gate + if: github.event_name == 'push' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: write + actions: read + id-token: write + attestations: write + artifact-metadata: write + env: + TAG: ${{ needs.gate.outputs.tag }} + VERSION: ${{ needs.gate.outputs.version }} + steps: + - name: Check out the tagged source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Check the tag still names the verified commit + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + set -euo pipefail + tagged=$(gh api "repos/$GH_REPO/commits/$TAG" --jq .sha) + test "$tagged" = "$GITHUB_SHA" || { echo "tag $TAG moved to $tagged during the release" >&2; exit 1; } + + - name: Download the tested packages + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + run-id: ${{ needs.gate.outputs.run }} + github-token: ${{ github.token }} + name: release-dist + path: ${{ runner.temp }}/assets + + - name: Prepare notes and checksums + run: | + set -euo pipefail + cd "$RUNNER_TEMP/assets" + for name in "harmonizepy-$VERSION-py3-none-any.whl" "harmonizepy-$VERSION.tar.gz"; do + test -s "$name" || { echo "missing tested package: $name" >&2; exit 1; } + done + count=$(find . -maxdepth 1 -type f | wc -l) + test "$count" -eq 2 || { echo "expected the 2 tested packages, found $count files: $(ls)" >&2; exit 1; } + sha256sum ./*.whl ./*.tar.gz > SHA256SUMS + sha256sum --check SHA256SUMS + cd "$GITHUB_WORKSPACE" + bash .github/scripts/release.sh notes "$TAG" > "$RUNNER_TEMP/notes.md" + + - name: Create or resume the draft release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: | + set -euo pipefail + if draft=$(gh release view "$TAG" --json isDraft --jq .isDraft 2> "$RUNNER_TEMP/view.err"); then + test "$draft" = true || { echo "release $TAG is already published" >&2; exit 1; } + elif grep -q "release not found" "$RUNNER_TEMP/view.err"; then + gh release create "$TAG" --draft --verify-tag --title "HarmonizePy $VERSION" --notes-file "$RUNNER_TEMP/notes.md" + else + cat "$RUNNER_TEMP/view.err" >&2 + exit 1 + fi + gh release upload "$TAG" "$RUNNER_TEMP/assets"/* --clobber + + - name: Attest the release packages + uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 + with: + subject-checksums: ${{ runner.temp }}/assets/SHA256SUMS + + - name: Publish the release + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: gh release edit "$TAG" --draft=false --latest --verify-tag diff --git a/.gitignore b/.gitignore index b2687b4..249753d 100644 --- a/.gitignore +++ b/.gitignore @@ -54,3 +54,5 @@ renv/sandbox/ *.swo *~ .DS_Store + +*.svg \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 474a939..d035936 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,143 +2,139 @@ # Changelog -All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +All notable changes to HarmonizePy, newest first. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +How to read it: + +- Each version opens with a summary of what it changes for users. The entries follow under **Added**, **Changed**, **Fixed**, and **Removed**, each led by the area it touches. +- While the major version is 0, a minor version can change corrected values. Every intended change is listed. +- `#N` is the GitHub issue with the discussion. Work on `main` that is not released yet collects under `[Unreleased]`. +- From 0.4.0, a version's section is also the text of its GitHub release. ## [Unreleased] +## [0.4.0] - 2026-11-22 + +This release fixes the inputs found to give wrong values, hang, or fail without a clear message, and adds a report that says what happened to each feature. Corrected values change only where a fix below applies; elsewhere they differ from 0.3.2 by rounding, at most 1e-10. Large inputs run faster and need less memory. + +### Added + +- **Correction report.** `harmonize(..., return_report=True)` returns a `HarmonizeResult` of the corrected matrix and a table with one row per feature: whether it was corrected or kept raw and why, the batches of its group, its group size, whether unique removal cropped it, and how many repeats of it were removed. The CLI writes the same table with `--report PATH`. The matrix is the same with or without the report (#28). +- **Input-scale warning.** `harmonize()` and the dry run warn with `InputScaleWarning` when the values look untransformed (non-negative with a 95th percentile above 100) or look like proportions, and name the transform to apply. The check is a heuristic and can be silenced by category (#25). +- **Releases.** Pushing a `vX.Y.Z` tag publishes a GitHub release once `main`'s CI has passed on the tagged commit: the wheel and sdist that CI built and smoke-tested, their SHA-256 checksums with an attestation, and this file's section as the notes. + +### Changed + +- **Speed and memory.** ComBat solves all batches of a group together, computes the non-parametric prior in blocks sized for the CPU cache, and checks for features to leave raw in a few array operations per group. Corrected values change by rounding only. +- **One thread.** CSV and TSV files are read with pandas' C parser instead of pyarrow's reader, which started a thread pool, and Parquet is read without reader threads. The `io` extra is needed for Parquet only. +- **Logging.** The per-group ComBat line is at DEBUG level; INFO lines report the number of groups. + +### Fixed + +- **ComBat statistics.** + - A feature whose variance the engine would raise to its 1e-12 floor, such as one constant inside a batch, keeps its raw values and no longer sets the empirical-Bayes prior for every other feature (#18). In modes 2 to 4, a feature constant in only some batches is still corrected; `sva::ComBat` leaves it raw. + - Modes 3 and 4 form each likelihood from the deviations to the feature's own mean, as `sva::ComBat` does. The expanded form lost precision and could put scale estimates off by up to a factor of three. + - `combat()` and `remove_batch_effect()` fit a feature that has no value in some batch on the batches it was measured in; the unobserved batch counted as a batch effect of zero, so a true level of 10 came back near 7. Features with values in a single batch keep their raw values, as do, in limma, features missing a batch whose values do not outnumber their observed batches. `harmonize()` never sends such a feature to an engine, so this change alone does not alter its output (#27). +- **Features left raw.** A feature alone in its batch pattern keeps its raw values with both engines. ComBat could hang on such a row with a missing cell, and limma corrected it on its own batch means (#19). limma also leaves raw a feature with no more values than batches it is observed in, reported `raw_too_few_values`; such a fit collapsed it to one level. +- **Unique removal.** + - A feature with an affiliation of its own may move into the affiliation of a single other feature, which keeps it, as HarmonizR allows; with many batches the narrower rule left many features raw. Features are taken longest affiliation first, and a feature with no target keeps its values, where HarmonizR empties it (#23). + - Between equally long targets, the one more features hold wins, then the smallest; the choice depended on the order of the rows, so reordering them could change the groups and the corrected values. + - A feature is never moved into an affiliation that spans a single batch: such a group is left raw, so the move only emptied the feature's other values. +- **Engine input.** `combat()` keeps a feature with no value missing instead of making every value missing. Infinite values are rejected with the feature named. All four engine functions require whole-number batch labels; `combat()` merged labels such as 0.2 and 0.9 into one batch. An unknown `ref_batch`, a one-sample reference batch, an unknown algorithm, and a `combat_mode` other than an integer from 1 to 4 are rejected with one message each. `needed_values` must be a whole number of at least 1; 2.5 acted as 3 and `True` as 1. ComBat rejects values of magnitude 1e150 or more, whose squares overflow its variance sums, naming the features; limma accepts them. +- **Input files.** + - A whole-number column with a blank cell loads, with the blank as missing (#20). + - A feature is removed as a repeat only when its name and all its values repeat, and the removal is logged; a name repeated with different values raises a `ValueError`. Files and DataFrames follow the same rule (#21). + - Rows with no value are kept when a file is read, as for a DataFrame; reading a file dropped them. Repeated sample names raise a `ValueError`. + - The batch description is read by one rule everywhere: the columns named `ID` and `batch`, otherwise the first and third. A sample listed twice, or a batch label that is not a whole number, raises a `ValueError` that names it (#22). +- **Names as written.** Feature names and the description's sample IDs are read as text: a feature named `NA` or `null` keeps its name, where it was read as missing and could be removed as a repeat of another such feature, and IDs such as `01` match columns named `01`. A DataFrame with integer column labels matches text IDs instead of failing with a `KeyError`, and `block` accepts NumPy integers. +- **Seriation order.** `sort="seriation"` gives the same batch order for any order of the rows; batches whose scores tied in magnitude were ordered by rounding, so with `block` the missing cells of the output could change when the rows were shuffled. +- **Output files.** The corrected matrix, the report, and the summary are written to a temporary file and renamed, so a failed write leaves no partial file and keeps the previous one. +- **Command line.** `--output-format csv` without `-o` writes a `.csv` file. A dry run writes no files, plans the groups exactly as the run does, and prints the `needed_values` the run uses; `--dry-run` with `--log-file`, `--summary`, `--json`, or `--report` is a usage error (#22). The summary records the resolved `needed_values`; a malformed YAML config and read or write errors give a message instead of a traceback; log lines are not repeated when `main()` runs twice. No output (`-o`, `--summary`, `--report`, or the log file) may name an input file or another output; `-o` and `--summary` could overwrite the data file. Config file values are checked like the matching flags, so an invalid one is a usage error (exit 2). +- **Pipeline.** The log counts the features unique removal moved and the blocks correctly. `build_block_list()` accepts float labels and counts them as distinct batches; `build_affiliation_list()` checks that labels match the columns. limma's log no longer counts a feature with no value as one with values in a single batch. +- **Documentation.** Docstrings, CLI help, the wiki, the README, and the parity document describe what the code does, and state the sort-order and unique-removal differences from HarmonizR with how often the results agree (#24). The CLI help says Parquet feature names are the index, and the README makes no sample-size or batch-count recommendation that no measurement supports. + ## [0.3.2] - 2026-05-29 +This release adds a GitHub wiki, a CI workflow that runs the R concordance tests on committed fixtures, and a benchmark summary. + ### Added -- Fixture-backed CI workflow with a representative test subset for push and pull request runs. -- Top-level benchmark results documentation now summarizes dataset design, benchmark environment, R-vs-Python representative runtimes, and the mixed R-backed versus Python-only benchmark policy. -- GitHub Wiki documentation added under `docs/`: 10 pages covering Installation, Quick Start, Input Format, Algorithms, Pipeline, API Reference, CLI Reference, R Compatibility, and Benchmarks. Includes `_Sidebar.md` and `_Footer.md` for navigation. +- **CI.** A GitHub Actions workflow runs a representative subset of the test suite on pushes and pull requests, with the R reference outputs committed so the concordance tests need no R installation. +- **Documentation.** A GitHub wiki of ten pages (installation, quick start, input format, algorithms, pipeline, API, CLI, R compatibility, benchmarks) and a benchmark summary in `benchmarks/RESULTS.md`. ### Changed -- R-generated TSV and CSV fixtures are now tracked in git so CI can run concordance coverage without regenerating them. -- Package metadata, smoke checks, README examples, parity docs, and workspace reference docs are aligned on version 0.3.2. -- CLI default output now writes `_corrected.tsv` unless parquet is explicitly requested. -- README restructured: intro condensed, Documentation section added with wiki links, parameter table trimmed to most-used params, CLI section shortened, test coverage and project layout sections condensed. Logo uses absolute GitHub raw URL for PyPI compatibility. Docs badge links to the wiki. +- **Command line.** Without `-o`, the output is `_corrected.tsv`; Parquet is written only when requested. +- **README.** The README is shorter and links to the wiki pages. ### Fixed -- Repo-wide Ruff and mypy failures cleared on the current CI target. -- Install docs and dependency notes now document `harmonizepy[io]` for parquet support and pyarrow-accelerated IO. +- **Code quality.** Ruff and mypy pass on the CI target. The install docs name the `io` extra for Parquet. ## [0.3.1] - 2026-05-28 +This release adds a benchmark harness that compares against HarmonizR, and speeds up the missing-value paths of both engines. + ### Added -- New benchmark system: in-process runner, YAML-driven scenario registry, stable R cache keys, 6-command CLI (`run`/`cache-r`/`validity`/`profile`/`report`/`generate-data`), and JSON/Markdown report generation. -- Per-scenario validity checks, R concordance in the harness, and scenario tags (`parametric`, `nonparametric`, `blocking`, `sorted`, `py_only`) for filtering. -- Comparable memory metrics: R heap and RSS delta alongside Python tracemalloc including output array `nbytes`. -- R wrapper recovers from `sva::ComBat` singular matrix crashes by removing problematic features and retrying. +- **Benchmarks.** A benchmark command (`run`, `cache-r`, `validity`, `profile`, `report`, `generate-data`) with a scenario registry, cached HarmonizR baselines, concordance checks, and memory measurements for Python and R. ### Changed -- `splitting.py` and `core.py`: keep split-and-rebuild on one final assembled matrix, cache per-affiliation column indices, and for sorted runs scatter corrected submatrices directly back to original column positions instead of reordering the full result afterwards. -- Internal optimization and benchmark-status documents reorganized to separate completed work from remaining memory-focused items. -- Benchmarking now uses public `harmonize()` directly, defaults R baselines to 1 core, suppresses timed-run logging, and auto-converts DIA CSV input to TSV for R. +- **Speed.** The ComBat missing-value path, the non-parametric prior, the limma missing-value path, the affiliation and sorting helpers, data validation, and output assembly do less repeated work, with concordance unchanged. ### Fixed -- Orphaned `doParallel` workers killed via process group on R timeout. -- R version strings cleaned of renv status messages. -- `generate_from_config` uses per-dataset `missing_frac` instead of hardcoded 0.0. -- `block` passed to HarmonizR as numeric (was silently falling back to unblocked). Historical `Block = 2` results invalidated. -- Memory/reporting fixes: tracemalloc MB divisor corrected from 1e6 to 1024^2, and R `gc()` now reads the MB column instead of raw cell counts. -- CLI/config fixes: config paths now resolve relative to the config file, and `--combat-modes` now reaches `filter_registry` in `run`, `cache-r`, and `validity`. -- Harness batch column lookup uses column name with positional fallback matching `core.py`. -- Dead code removed: `Scenario.cache_key`, `phase_times` field and aggregation. - -### Performance - -- `_combat_nan`: consolidated NaN-heavy ComBat work including vectorized standardization/final adjustment, grouped valid-mask reuse, one-hot grouped Beta.NA with reused reduced layouts, grouped row variance by sums/squared sums, and reusable `_it_sol` buffers. These changes reduced engine overhead while preserving concordance. -- Non-parametric ComBat: binomial residual precompute plus block-vectorized `_int_eprior` cut large mode 3 from 9.76s to 5.87s. -- limma NaN path now groups identical valid-observation masks and solves each reduced design once, improving representative full-pipeline timings from 0.48s to 0.27s on murine and from 1.13s to 0.36s on DIA while preserving concordance. -- Affiliation and sorting helpers now reuse repeated affiliation patterns and precomputed non-NaN presence masks, reducing representative sorted/block timings from 0.15s to 0.13s on medium ComBat mode 1 and from 2.80s to 2.65s on `scp_large` limma. -- Data-matrix validation now inspects `df.dtypes` directly instead of indexing every column, reducing `validate_data_matrix()` on `scp_large` from 0.90s to 0.05s and improving representative `scp_large` limma sort+block timing from 2.72s to 2.35s without changing concordance. -- `splitting()` now returns its assembled output with `DataFrame(..., copy=False)`, removing the final full-width materialization copy and improving representative `scp_large` limma sort+block timing from 2.38s to 2.07s. -- The split path now reuses one float64 ndarray across affiliation spotting and extraction, removing a duplicate whole-frame conversion and improving representative `scp_large` limma sort+block timing from 2.24s to 1.96s. -- Direct-assembly and column-cache refactors improved pipeline timings: medium limma 0.15s->0.09s, medium m1 0.69s->0.63s, scp_small limma 0.16s->0.13s, scp_small m1 0.36s->0.32s. -- Sorted block runs now avoid a full final unsort copy, improving representative `scp_large` timings from 5.87s to 5.57s for ComBat mode 1 and from 3.87s to 3.66s for limma. +- **Benchmarks.** `block` reaches HarmonizR as a number (it fell back to no blocking, so earlier blocked R results were invalid); memory units, R version strings, config paths, mode filters, and R worker clean-up on timeout are corrected. ## [0.3.0] - 2026-05-27 +Per-cell missing values reach the engines instead of being dropped: each feature is corrected from its observed cells, as `sva::ComBat` 3.60.0 does, where rows and columns with missing cells were dropped before. + ### Added -- NaN handling: per-feature Beta.NA computation in ComBat and limma engines, matching R sva v3.60.0. NaN-shaped sub-matrices pass through to engines; each feature independently omits NaN from OLS, variance, and EB computations. -- NaN-safe iterative (`_it_sol`) and non-parametric (`_int_eprior`) EB solvers using per-gene non-NA counts. -- Per-cell NaN R concordance fixtures and murine medulloblastoma real-data verification. All modes concordant at max_rel 0.0003. -- FEATURE_PARITY.md with complete R vs Python difference inventory. -- DIA real-proteomics dataset verification: 8470 proteins, 2 batches, perfect concordance at machine epsilon. +- **Missing values.** ComBat and limma compute each feature's batch means, variances, and empirical-Bayes estimates from its observed cells (`Beta.NA`), and both solvers use each feature's own count of observed cells. +- **Validation.** R concordance fixtures with per-cell missing values, checks on the murine medulloblastoma and DIA proteomics datasets, and `assets/FEATURE_PARITY.md`, the list of differences from HarmonizR. ### Changed -- Engine NaN handling: replaced row-dropping with per-feature Beta.NA path. Dense path unchanged. -- `splitting.py`: removed column-dropping logic. Per-cell NaN flows through to engines. -- `validation.py`: NaN allowed in engine inputs; validation checks only structural properties. -- Test NaN invariants: now verify correct NaN handling rather than asserting NaN-free input. -- Code cleanup: removed redundant copies, consolidated duplicated helpers, vectorized block assignment. -- Benchmark runner: R memory measurement and expanded concordance metrics. +- **Pipeline.** Sub-matrices keep their missing cells; rows and columns are no longer dropped before correction, and engine input may contain missing values. ### Fixed -- `_it_sol`: `t2_n_g_hat` uses original `g_hat` per iteration (not updated `g_new`), matching R's `postmean` formula. Prevents divergence with NaN data. -- `_int_eprior`: likelihood normalization uses per-gene `n_i` instead of fixed batch size. Enables correct non-parametric EB with per-cell NaN. -- Benchmark data generator: minimum 4 samples per batch to satisfy needed_values=2. -- Benchmark runner: unique tagged filenames per scenario, R memory measurement via `/usr/bin/time -v`. -- Dry-run mode: pipeline DEBUG suppressed during plan output. - -### Performance - -Modes 1/2 run in ~1.3-1.7s on 8470x36 data. Modes 3/4 dominate at ~8.5s (80% spent in `_int_eprior` broadcast loop). Targets: binomial formula for `_int_eprior` (est. 2.8x on modes 3/4), grouped NaN-pattern solving for per-feature OLS/variance. +- **ComBat solvers.** The parametric solver uses the original batch estimate in each iteration, as R's `postmean` does, which stops it diverging on missing data; the non-parametric prior normalises each likelihood by the feature's own observed count. +- **Command line.** The dry run no longer prints pipeline debug lines. ## [0.2.0] - 2026-04-01 +This release builds the HarmonizR pipeline around the engines, after HarmonizR 1.8.0: batch sorting, blocking, and unique-combination removal, with a command line. + ### Added -- **Batch sorting**: three strategies matching R HarmonizR v1.8.0: sparsity (completeness-based), jaccard (greedy nearest-neighbour), seriation (PCA-based optimal leaf ordering). See `harmonizepy.sorting`. -- **Batch blocking**: group consecutive batches into superblocks for dissection via `block=N`. See `harmonizepy.blocking`. -- **Unique-combination removal**: rescue singleton features by cropping to the nearest shared batch-presence pattern (`unique_removal=True`, matching R's `ur=TRUE` default). See `harmonizepy.affiliation`. -- **CLI** (`__main__.py`): full command-line interface with positional args, `--algorithm`, `--combat-mode`, `--sort`, `--block`, `--unique-removal`, `--needed-values`, `--dry-run`, `--summary`, `--json`, `--config`, `--verbose`/`--quiet`, `--version`, `--help`. Output formats: TSV, CSV, Feather. -- **`HarmonizeConfig`** frozen dataclass for reproducible run configuration. -- **`validate_harmonize_args`** centralised validation of all pipeline parameters. +- **Pipeline.** Batch sorting (`sparsity`, `jaccard`, `seriation`), blocking of neighbouring batches (`block=N`), and unique-combination removal (`unique_removal=True`, after R's `ur=TRUE`). +- **Command line.** The `harmonizepy` command with the pipeline options, `--needed-values`, `--dry-run`, `--summary`, `--json`, `--config`, and TSV, CSV, and Feather output. +- **Configuration.** `HarmonizeConfig`, a frozen dataclass for a reproducible run, and one validator for all pipeline arguments. ### Changed -- **`harmonize()` pipeline** (`core.py`): extended from direct ComBat/limma adjustment to the full HarmonizR workflow: sort, block, spot missing, unique removal, split, adjust, concat, re-sort columns. -- **Splitting** (`splitting.py`): pre-allocates a single output array instead of one per affiliation group, reducing peak memory from ~3x input to ~1x input. -- **Input validation** (`validation.py`): extracted from individual modules into a single file with consistent error messages. -- **IO** (`io.py`): now reads TSV, CSV, and Feather formats; drops all-NaN rows on read; preserves all-NaN columns (structural missingness). +- **Memory.** The split step fills one output array instead of one per group, so peak memory is about the input's size instead of three times it. +- **Input.** Files are read as TSV, CSV, or Feather. ### Removed -- Redundant validation spread across `combat.py` and `limma_wrapper.py`, consolidated into `validation.py`. -- `np.matrix` usage from ComBat engine, now fully vectorised NumPy. +- **Engines.** The ComBat engine no longer uses `np.matrix`, and validation repeated across modules is gone. ### Fixed -- `_int_eprior` in `combat.py`: guard against zero/negative `d_hat` causing `-inf` in log-likelihood computation (clamp to `1e-12`). -- `_aprior` / `_bprior`: return flat prior (`1.0`) when variance cannot be estimated (zero-variance features). -- `combat()`: force `mean_only=True` when any batch has fewer than 2 samples (mirrors R `sva::ComBat` behaviour). -- `combat()`: negative `delta_star` from `_postvar` clamped before `sqrt`. - -### R Concordance - -- Full test suite validated against R `sva::ComBat`, `limma::removeBatchEffect`, and `HarmonizR` (v1.8.0 pipeline with sort, block, and unique-removal toggles). Covers small, medium, large, unbalanced, minimal, high-var, near-constant, negative, wide, sparse, high-missingness, and singleton-batch edge cases. +- **ComBat.** A zero or negative scale estimate no longer gives an infinite log-likelihood or a negative variance, the priors stay finite for zero-variance features, and a one-sample batch forces location-only correction, as `sva::ComBat` does. ## [0.1.0] - 2025-12-15 +The first release implements ComBat in its four modes and limma's `removeBatchEffect` in NumPy, with the HarmonizR approach to missing values (split by batch pattern, correct, reassemble), tested against R. + ### Added -- **ComBat engine** (`combat.py`): pure NumPy reimplementation of Johnson, Li & Rabinovic (2007). All four modes: parametric and non-parametric, with and without scale correction. Supports `ref_batch` and automatic `mean_only` fallback for singleton batches. -- **limma engine** (`limma_wrapper.py`): pure NumPy `removeBatchEffect` using sum-to-zero contrasts and OLS (Ritchie et al. 2015). -- **HarmonizR pipeline** (`core.py`): structural missingness handling via per-feature batch presence detection, grouping by affiliation, NaN-free sub-matrix extraction, adjustment, and reassembly. -- **`harmonize()` entry point**: accepts DataFrames, file paths (TSV/CSV), and Path objects. -- **Data IO** (`io.py`): `read_main_data`, `read_description`, `write_output` for TSV/CSV. -- **Input validation**: `validate_data_matrix`, `validate_description`, `validate_combat_input`, `validate_limma_input`. -- **CLI** (`__main__.py`): minimal command-line wrapper with `-o` output flag. -- **Test suite**: R-concordance tests for all ComBat modes and limma, plus unit tests for all internal helpers. -- **R fixture generation**: scripts under `tests/fixtures/` generating reference outputs from R `sva`, `limma`, and `HarmonizR`. +- **Engines.** ComBat (Johnson, Li & Rabinovic 2007), parametric and non-parametric, with and without scale correction, with `ref_batch`; limma's `removeBatchEffect` with sum-to-zero contrasts (Ritchie et al. 2015). +- **Pipeline.** `harmonize()` groups features by the batches they are observed in, corrects each group, and reassembles the matrix; it accepts DataFrames and TSV or CSV paths. +- **Command line.** A minimal `harmonizepy` command with `-o`. +- **Tests.** Concordance tests against R `sva`, `limma`, and HarmonizR, with the scripts that generate the reference outputs. diff --git a/CITATION.cff b/CITATION.cff index 11502ab..8fcd38d 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -3,35 +3,36 @@ title: "HarmonizePy: Pure-Python batch-effect harmonization with structural miss message: "If you use HarmonizePy in your research, please cite it using the metadata below." type: software repository-code: "https://github.com/LangeLab/HarmonizePy" -version: 0.3.2 -date-released: "2026-05-29" +version: 0.4.0 +date-released: "2026-11-22" license: GPL-3.0 abstract: > HarmonizePy is a Pure-Python batch-effect correction toolkit for omics - data with structural missingness. Standard ComBat and limma require - complete matrices; HarmonizePy handles the dissection, adjustment, and - reassembly so they work on real-world incomplete data without an R - runtime. + data with structural missingness. It splits the matrix by each feature's + pattern of observed batches, adjusts each part, and reassembles it, so + that features missing from whole batches are corrected without + imputation and without an R runtime. It provides all four modes of ComBat (Johnson, Li & Rabinovic, 2007): parametric and non-parametric, with and without scale correction. It also implements limma-style batch removal via sum-to-zero contrasts - (Ritchie et al., 2015). The pipeline targets HarmonizR v1.10.0 feature - parity: per-feature batch-presence detection groups the matrix into + (Ritchie et al., 2015). The pipeline follows HarmonizR v1.10.0, with + documented differences: per-feature batch-presence detection groups the matrix into compatible subsets, each adjusted independently and then reassembled into the original shape without imputation. Missing observations remain missing in the output. Three sort strategies reorder batches so similar ones become neighbours before blocking; batch blocking groups consecutive batches into blocks to reduce sub-matrix count and memory; unique-combination removal rescues singletons by cropping their - affiliation to the nearest shared pattern before splitting. + affiliation to another feature's pattern before splitting. The engine layer is pure NumPy with no compiled extensions. Both a programmatic API and a full CLI are available, supporting config files - (TOML, JSON, YAML), dry-run validation, JSON run summaries, and output - in TSV, CSV, or Parquet. The implementation is verified against R + (TOML, JSON, YAML), dry-run validation, JSON run summaries, a + per-feature report of what happened to each feature, and output in TSV, + CSV, or Parquet. The implementation is verified against R reference outputs for `sva::ComBat`, `limma::removeBatchEffect`, and HarmonizR workflows across synthetic and real-data scenarios. authors: diff --git a/README.md b/README.md index 3ce24ee..6a7875a 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@

Python 3.12-3.14 - v0.3.2 + v0.4.0 Alpha CI Coverage @@ -48,14 +48,52 @@ HarmonizePy is a pure-Python batch-effect correction package for omics data. The **limma** (Ritchie et al. 2015). Linear-model batch correction via sum-to-zero contrasts. -**HarmonizR-compatible pipeline (feature parity with v1.10.0):** +**HarmonizR pipeline (follows v1.10.0; the differences are listed in [R Compatibility](https://github.com/LangeLab/HarmonizePy/wiki/R-Compatibility)):** - Structural missingness handled automatically: features are grouped by observed batch support, corrected in compatible subsets, and reassembled into the original matrix shape. -- Batch sorting: reorder batches so similar ones become neighbours. Three strategies: `"sparsity"` (completeness-based, fastest), `"jaccard"` (pairwise feature-overlap similarity), `"seriation"` (PCA-based ordering, more accurate for many batches). -- Batch blocking: group `block=N` consecutive (optionally sorted) batches into a single sub-matrix, reducing peak memory and improving adjustment quality for datasets with many batches. -- Unique-combination removal (`unique_removal=True`, default): features whose batch-presence pattern is unique across the dataset get rescued. They would otherwise form a singleton sub-matrix and be dropped. The algorithm crops their affiliation to the nearest shared pattern, trading some non-missing data for inclusion in a group adjustment. +- Batch sorting: reorder batches so that similar ones become neighbours before blocking. Three strategies: `"sparsity"` (number of features present), `"jaccard"` (overlap of present features), `"seriation"` (first principal component of the presence vectors). +- Batch blocking: group `block=N` neighbouring batches when forming sub-matrices. A feature needs enough values in every batch of a block for the block to count, so blocking trades observed values for fewer, larger groups. The engines still correct each batch. +- Unique-combination removal (`unique_removal=True`, default): a feature whose batch-presence pattern no other feature shares would form a group of one and keep its raw values. Its affiliation is cropped to the longest affiliation of another feature within its own (spanning at least two batches), trading the values in the dropped blocks for a group correction. -**Validation against R reference workflows:** the package is tested against `sva::ComBat`, `limma::removeBatchEffect`, and HarmonizR v1.10.0 reference outputs. Known edge-case differences in retention policy are documented in the [R Compatibility](https://github.com/LangeLab/HarmonizePy/wiki/R-Compatibility) wiki page. Runtime benchmarks across six datasets are in [Benchmarks](https://github.com/LangeLab/HarmonizePy/wiki/Benchmarks). +**Validation against R reference workflows:** the package is tested against `sva::ComBat`, `limma::removeBatchEffect`, and HarmonizR v1.10.0 reference outputs. Known edge-case differences in retention policy are documented in the [R Compatibility](https://github.com/LangeLab/HarmonizePy/wiki/R-Compatibility) wiki page. Runtime benchmarks across seven datasets are in [Benchmarks](https://github.com/LangeLab/HarmonizePy/wiki/Benchmarks). + +## Performance + +The same correction as HarmonizR 1.10.0, on the same matrices, in a fraction of the time: + +

+ + + + + Wall time of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy takes 21 ms to 2.0 s, HarmonizR 1.0 s to 312 s, 3.9 to 338 times longer + + +

+ +| Dataset | Features x samples | HarmonizePy | HarmonizR | Faster | Largest difference | +| ----------- | ------------------ | ----------: | --------: | -----: | -----------------: | +| `small` | 1,000 x 20 | 0.11 s | 7.6 s | 67x | 6e-06 | +| `murine` | 4,753 x 25 | 0.47 s | 1.8 s | 3.9x | 3e-04 | +| `medium` | 5,000 x 60 | 2.0 s | 14 s | 7.0x | 0.42\* | +| `dia` | 8,470 x 36 | 0.49 s | 4.8 s | 9.9x | 5e-15 | +| `scp_small` | 3,000 x 1,000 | 0.71 s | 59 s | 82x | 7e-06 | + +ComBat mode 1, the default, both on one core; the largest difference is the largest relative difference between the two outputs over the cells both have, and mode 1's solver stops at a 1e-4 convergence threshold. \* On `medium` without blocking, the two unique-removal rules take features in a different order, so some features join different groups. [Benchmark results](benchmarks/RESULTS.md) has every scenario, the scaling sweeps, and the method. + +It also needs less memory. Each tool runs in a fresh process that reads both files, corrects once and exits: + +

+ + + + + Peak memory of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy 116 to 208 MB, HarmonizR 170 to 848 MB, 1.4 to 5.9 times more + + +

+ +HarmonizePy peaks at 116 to 208 MB; HarmonizR needs 1.4 to 2.6 times that with limma and 3.8 to 5.9 times with ComBat, most of it the sva package it loads. ## Installation @@ -71,16 +109,16 @@ uv python install 3.12.13 uv sync --dev --python 3.12.13 # Optional extras -pip install harmonizepy[config] # YAML/TOML support for --config flag +pip install harmonizepy[config] # YAML config files for --config pip install harmonizepy[completion] # Shell tab-completion via argcomplete -pip install harmonizepy[io] # Parquet IO and pyarrow-accelerated CSV/TSV paths +pip install harmonizepy[io] # Parquet input and output ``` See [Installation](https://github.com/LangeLab/HarmonizePy/wiki/Installation) for the full dependency list and optional extras detail. ## Quick start -`harmonize()` returns a `pandas.DataFrame` with the same shape and column order as the input. Features are rows (DataFrame index), samples are columns. +`harmonize()` returns a `pandas.DataFrame` with the input's features and column order; a feature repeated with the same name and values appears once. Features are rows (DataFrame index), samples are columns. ```python import pandas as pd @@ -95,6 +133,10 @@ data_df = pd.read_csv("data.tsv", sep="\t", index_col=0) desc_df = pd.read_csv("description.csv") result = harmonize(data_df, desc_df, algorithm="limma", sort="sparsity", block=2) +# What happened to each feature: corrected, or kept raw and why +result, report = harmonize(data_df, desc_df, return_report=True) +report["status"].value_counts() + # Low-level API (ndarray in, ndarray out) from harmonizepy import combat, remove_batch_effect @@ -106,8 +148,8 @@ The low-level engines handle missing observations per feature and preserve NaN p ### Input format -- **data**: features × samples matrix. For TSV/CSV files, the first column must contain feature names (read as the DataFrame index). When passing a DataFrame directly, feature names must be in `DataFrame.index` and sample names in `DataFrame.columns`. -- **description**: CSV/DataFrame with columns `ID` (sample names matching data columns), `sample` (integer), `batch` (integer batch label). +- **data**: features x samples matrix of log-transformed values, usually log2; HarmonizePy does not transform them, and warns with `InputScaleWarning` when the values look untransformed. For TSV/CSV files, the first column must contain feature names (read as the DataFrame index). When passing a DataFrame directly, feature names must be in `DataFrame.index` and sample names in `DataFrame.columns`. +- **description**: CSV/DataFrame with at least three columns: `ID` (sample names matching data columns), `sample` (not read), and `batch` (whole-number batch label). Without the names `ID` and `batch`, the first column holds the sample names and the third the batch labels. ### Parameter reference @@ -117,13 +159,14 @@ The low-level engines handle missing observations per feature and preserve NaN p | `combat_mode` | 1, 2, 3, 4 | 1 | ComBat variant (ignored for limma) | | `sort` | `"sparsity"`, `"jaccard"`, `"seriation"`, or `None` | `None` | Batch sorting strategy before blocking | | `block` | int >= 2 or `None` | `None` | Group N consecutive batches into one sub-matrix block | -| `unique_removal` | bool | `True` | Rescue singleton features by cropping to nearest shared pattern | +| `unique_removal` | bool | `True` | Crop singletons to another feature's pattern | +| `return_report` | bool | `False` | Also return the per-feature correction report | Full signature with all parameters is in the [API Reference](https://github.com/LangeLab/HarmonizePy/wiki/API-Reference). ### Choosing algorithm and strategy -Start with the default (`ComBat`, mode 1). For very small batch sizes (n < 10 per batch), prefer `combat_mode=3` (non-parametric). For datasets with 5 or more batches, `sort="sparsity"` and `block=2` group similar batches together before correction. Use `sort="jaccard"` when batch sizes are uneven. See [Algorithms](https://github.com/LangeLab/HarmonizePy/wiki/Algorithms) and [Pipeline](https://github.com/LangeLab/HarmonizePy/wiki/Pipeline) for full guidance. +Start with the default (`ComBat`, mode 1). The non-parametric modes (3 and 4) assume no distribution for the batch effects, at a cost that grows with the square of a group's size. Blocking (`block=N`) forms fewer, larger groups, at the cost of the values a feature has in only part of a block; sorting decides which batches share a block and has no effect without it. No measurement in this repository yet recommends one setting over another. See [Algorithms](https://github.com/LangeLab/HarmonizePy/wiki/Algorithms) and [Pipeline](https://github.com/LangeLab/HarmonizePy/wiki/Pipeline) for full guidance. ## CLI usage @@ -138,11 +181,14 @@ harmonizepy data.tsv batch.csv --combat-mode 3 --sort sparsity --block 2 -o corr # Validate inputs without running correction harmonizepy data.tsv batch.csv --dry-run -# Config file (TOML, JSON, or YAML with [config] extra) +# Also write what happened to each feature +harmonizepy data.tsv batch.csv -o corrected.tsv --report report.tsv + +# Config file (TOML or JSON; YAML needs the [config] extra) harmonizepy data.tsv batch.csv --config run.toml ``` -When `-o` is omitted, the output is written as `_corrected.tsv` next to the input file. See [CLI Reference](https://github.com/LangeLab/HarmonizePy/wiki/CLI-Reference) for all flags, output formats, and config file syntax. +When `-o` is omitted, the output is written next to the input file as `_corrected` with the extension of `--output-format` (`.tsv` by default). See [CLI Reference](https://github.com/LangeLab/HarmonizePy/wiki/CLI-Reference) for all flags, output formats, and config file syntax. ## Running tests @@ -159,7 +205,6 @@ The suite covers R concordance, edge cases, failure modes, numerical stability, src/harmonizepy/ # Package source: pipeline, engines, CLI, I/O tests/ # Unit, integration, R concordance, and CLI tests benchmarks/ # Benchmark CLI, dataset catalog, results -data/ # Small showcase datasets ``` ## License @@ -180,4 +225,4 @@ HarmonizePy is licensed under [GPL-3.0](LICENSE). - HarmonizR R package (Bioconductor): - HarmonizR source (GitHub): -The ComBat algorithm was introduced by Johnson, Li & Rabinovic (2007). `limma::removeBatchEffect` was published by Ritchie et al. (2015). The HarmonizR pipeline (structural-missingness handling, batch sorting, blocking, unique-combination removal) was developed by Voß et al. (2022) and Schlumbohm, Neumann & Neumann (2025). HarmonizePy is not a line-by-line port of the R sources: the engine logic was reimplemented from the published manuscripts and validated against R reference output. +The ComBat algorithm was introduced by Johnson, Li & Rabinovic (2007). `limma::removeBatchEffect` is part of the limma package, described by Ritchie et al. (2015). The HarmonizR pipeline (structural-missingness handling, batch sorting, blocking, unique-combination removal) was developed by Voß et al. (2022) and Schlumbohm, Neumann & Neumann (2025). HarmonizePy is not a line-by-line port of the R sources: the engines are reimplemented in NumPy from the published methods and the behaviour of the R packages, and validated against R reference output. diff --git a/assets/FEATURE_PARITY.md b/assets/FEATURE_PARITY.md index cec0a1a..b861d21 100644 --- a/assets/FEATURE_PARITY.md +++ b/assets/FEATURE_PARITY.md @@ -1,18 +1,17 @@ -# Feature Parity: R HarmonizR v1.10.0 vs HarmonizePy v0.3.2 +# Feature Parity: R HarmonizR v1.10.0 vs HarmonizePy v0.4.0 -References: R source at `ref/HarmonizR/R/` (13 files). R sva v3.60.0, limma, HarmonizR v1.10.0 via Bioconductor 3.23. +References: the HarmonizR v1.10.0 R sources (13 files), sva 3.60.0, and limma, from Bioconductor 3.23. --- ## Current Validation Boundaries -The parity surface is broader than the original structural-missingness fixture suite. In addition to the dense and structural-missingness fixtures, the repository now includes dedicated checks for per-cell NaN handling, medium `jaccard` and `seriation` sort+block cases, chain-rescue `unique_removal` toggles, and the combined stress case (`sort + block + ur + per-cell NaN`). +Besides the dense and structural-missingness fixtures, the repository has dedicated checks for per-cell NaN handling, medium `jaccard` and `seriation` sort+block cases, chain-rescue `unique_removal` toggles, and the combined stress case (`sort + block + ur + per-cell NaN`). -Remaining limits are narrower: +Limits: - Jaccard and seriation are fixture-backed and unit-tested, but exact algorithm matching to R is intentionally out of scope. -- Combined-stress validation is now fixture-backed, but exact NaN-position parity on every feature is still not used as a release gate because of the documented mixed-NaN edge case. -- Python source coverage is now measured directly in-repo and is currently 94% for `src/harmonizepy`. +- Combined-stress validation is fixture-backed, but exact NaN-position parity on every feature is not a release gate: the sort order and the unique-removal rule differ from R (sections 3 and 4), which changes the groups of some features. --- @@ -22,16 +21,16 @@ Remaining limits are narrower: All four ComBat modes and limma are concordant with R on both dense synthetic data and real murine data with per-cell NaN. NaN handling uses per-feature computation (Beta.NA per-feature OLS), NOT row dropping or column dropping. -| Mode | Dense rtol | Murine max_rel | Murine NaN match | -| ------------------------------------ | ---------- | -------------- | ---------------- | -| ComBat 1 (parametric, loc+scale) | 2e-5 | 0.0003 | YES | -| ComBat 2 (parametric, loc only) | 1e-9 | 0.0000 | * | -| ComBat 3 (non-parametric, loc+scale) | 5e-4 | 0.0000 | YES | -| ComBat 4 (non-parametric, loc only) | 1e-9 | 0.0000 | * | -| limma removeBatchEffect | 1e-9 | 0.0000 | YES | -| ref_batch, auto mean_only | identical | identical | Code review | +| Mode | Dense test rtol | Murine max_rel | Murine NaN match | +| ------------------------------------ | --------------- | -------------- | ---------------- | +| ComBat 1 (parametric, loc+scale) | 1e-4 | 0.0003 | YES | +| ComBat 2 (parametric, loc only) | 1e-6 | 0.0000 | \* | +| ComBat 3 (non-parametric, loc+scale) | 1e-6 to 5e-4 | 0.0000 | YES | +| ComBat 4 (non-parametric, loc only) | 1e-6 | 0.0000 | \* | +| limma removeBatchEffect | 1e-10 | 0.0000 | YES | +| ref_batch, auto mean_only | identical | identical | Code review | -*Modes 2 and 4: R drops 229 extra features (interaction of mean_only with single-feature groups). Python retains as all-NaN. On shared features, values match perfectly. +\*Modes 2 and 4: HarmonizR returns 870 of the shared features entirely missing although the input has values for them; HarmonizePy corrects them. HarmonizR also drops 229 features that HarmonizePy keeps: 221 with one value in a single batch, kept raw, and 8 empty rows, kept missing. On the cells both return, the values agree to 7e-09. ### 1.2 NaN Handling: Per-Feature Beta.NA (VERIFIED ON REAL DATA) @@ -48,21 +47,21 @@ Beta.NA <- function(y, X) { HarmonizePy implements the equivalent per-feature NaN handling across all computation steps: -- **B.hat**: R uses `apply(dat, 1, Beta.NA, design)`. Python uses `_beta_na(y, design)` per feature. Verified on murine: max_rel 0.0003. -- **var.pooled**: R uses `rowVars(residuals, na.rm=TRUE)`. Python uses `_row_var_nan(residuals)` per feature. Verified on murine: max_rel 0.0003. -- **gamma.hat**: R uses `apply(s.data, 1, Beta.NA, batch.design)`. Python uses `_beta_na(y, design)` per feature. Verified on murine: max_rel 0.0003. -- **delta.hat**: R uses `rowVars(s.data[, i], na.rm=TRUE)` per batch. Python uses `_row_var_nan(s_data[:, idx])` per batch per feature. Verified on murine: max_rel 0.0003. -- **EB solver (parametric)**: R's `postvar`/`postmean` handle NaN per-feature via `n()` in postvar. Python's `_it_sol` is NaN-safe using `np.nansum` and per-feature non-NA count. Verified on murine: max_rel 0.0003. -- **EB solver (non-parametric)**: R's `int.eprior` uses `x <- sdat[i, !is.na(sdat[i, ])]` and `n <- length(x)` per gene. Python's `_int_eprior` uses per-gene non-NA count `n_i` for likelihood normalization. Verified on murine: max_rel 0.0000. -- **NaN in output**: Both keep NaN in the same positions as input. Murine: all match. +- **B.hat**: R uses `apply(dat, 1, Beta.NA, design)`. Python uses `_beta_na_grouped_batch_design`, the same per-feature batch means, computed for features with the same pattern of observed cells together. +- **var.pooled**: R uses `rowVars(residuals, na.rm=TRUE)`. Python uses `_row_var_nan_grouped(residuals)` per feature. +- **gamma.hat**: R uses `apply(s.data, 1, Beta.NA, batch.design)`. Python uses `_beta_na_grouped_batch_design` on the standardised data. +- **delta.hat**: R uses `rowVars(s.data[, i], na.rm=TRUE)` per batch. Python uses `_row_var_nan_grouped(s_data[:, idx])` per batch. +- **EB solver (parametric)**: R's `postvar`/`postmean` handle NaN per-feature via `n()` in postvar. Python's `_it_sol_batches` uses `np.nansum` and each feature's observed count, solving all batches of a group in one loop. +- **EB solver (non-parametric)**: R's `int.eprior` uses `x <- sdat[i, !is.na(sdat[i, ])]` and `n <- length(x)` per gene. Python's `_int_eprior` uses each feature's observed count `n_i` in the likelihood. +- **NaN in output**: missing input cells stay missing in both. -**Key insight**: R does NOT drop rows with NaN. It handles NaN per-feature throughout the computation. The `na.omit` behavior previously described in older versions of sva is NOT present in v3.60.0. HarmonizePy matches the per-feature approach exactly. +R does not drop rows with NaN in sva 3.60.0; it handles NaN per feature throughout, and so does HarmonizePy. **Murine dataset results** (4753 features, 25 samples, 4 batches, 49% missing): -- All 5 methods concordant at machine epsilon (max_rel 0.0003 or less) -- NaN positions match on all shared features (4479-4524 of 4753) -- The 274-229 features only in Python reflect the intentional retention policy (single-feature groups and per-cell NaN features kept as all-NaN) +- All 5 methods agree on the cells both return, to 3e-04 relative for ComBat mode 1, whose solver stops at a tolerance, and to 4e-11 or better for the others. +- Missing cells match on all shared features in limma and ComBat modes 1 and 3. In modes 2 and 4, HarmonizR returns 870 features entirely missing that HarmonizePy corrects. +- The 274 features present only in the Python output in modes 1 and 3 have no batch with two values; HarmonizePy keeps them as missing rows. In modes 2 and 4, which need one value per batch, the 229 such features are 221 with values in a single batch, kept raw, and 8 empty rows. --- @@ -74,29 +73,33 @@ R uses `original_batches_existence_counter` to count non-NA per batch within eac ### 2.2 Sub-Matrix Extraction -R selects rows by sorted integer affiliation index and columns by `which(block_list %in% vec_in_affil)`. Python selects rows by pre-computed row index array and columns by `np.isin(block_arr, affil)`. Equivalent. Both allow per-cell NaN to pass through to the engines. `splitting.py` does NOT filter columns or rows based on NaN presence. +R selects rows by sorted integer affiliation index and columns by `which(block_list %in% vec_in_affil)`. Python selects rows by a pre-computed row index array and columns by joining the column indices of the affiliation's blocks. Equivalent. Both allow per-cell NaN to pass through to the engines. `splitting.py` does NOT filter columns or rows based on NaN presence. ### 2.3 Adjustment Per Sub-Matrix - Single-batch sub-df: both pass through raw values. Equivalent. -- Single-feature sub-df: **R drops, Python pass-through** (KNOWN DIVERGENCE). +- Single-feature sub-df: **R drops, Python pass-through** with either engine (KNOWN DIVERGENCE). +- Constant feature (zero variance within a batch): both leave it out of the ComBat fit and return its raw values, with different rules. See section 5. - Multi-batch with per-cell NaN: both use per-feature computation (Beta.NA approach). Murine verified at max_rel 0.0003. -- Multi-batch, no NaN: both use vectorized path. 185 tests pass. -- **NaN position mismatch on ~1.5% of shared features** (medium dataset): affiliation logic matches R exactly, but output NaN positions differ on ~77/4968 features. Root cause is in ComBat engine's handling of mixed NaN patterns within a multi-feature sub-matrix. Non-NaN values match perfectly. Not observed on murine dataset. Documented as low-priority edge case. +- Multi-batch, no NaN: both use the vectorized path. +- **Unblocked `medium` benchmark**: 49 of 4968 shared features differ with limma and 99 with ComBat mode 1, 45 of them in their missing cells, counted as features with a relative difference above 1e-4 or a different missing pattern. The cause is the order in which the two unique-removal rules take features (section 4): with ComBat mode 1, 62 are features HarmonizePy cropped to a different target than HarmonizR, 33 are in groups whose members those moves change, and 4 are features HarmonizePy keeps raw as alone in their pattern. HarmonizR also drops 32 features that HarmonizePy returns. With `block=2`, ComBat agrees to 7e-06. +- **Features HarmonizR returns entirely missing**: in some modes HarmonizR returns features entirely missing although the input has values for them: 1256 of 3000 on `scp_small` in modes 3 and 4, and 870 on `murine` in modes 2 and 4. HarmonizePy corrects them; on the cells both return, the values agree to 5e-15 and 7e-09. ### 2.4 Reassembly -R uses `plyr::rbind.fill` (align by row name). Python uses pre-allocated array + `pd.concat`. Equivalent for same feature sets. Dropped features: R removes from output entirely, Python keeps as all-NaN (intentional divergence). +R uses `plyr::rbind.fill` (align by row name). Python uses pre-allocated array + `pd.concat`. Equivalent for same feature sets. Dropped features: R removes from output entirely, Python keeps as all-NaN (intentional divergence). Columns: R returns only the columns of the sub-matrices it rebuilt, starting with the first, so the columns of a batch that no group uses are missing from its output and the column order follows the groups; Python returns every input column in the input order. --- ## 3. Sorting Strategies -**Sparsity sort**: R `find_na()` sums NAs per batch, orders ascending. Python `_sparsity_order()` counts present features, orders descending. Inverse logic, same ordering. **Verified.** +**Sparsity sort**: R `find_na()` counts the missing cells of each batch and orders ascending. Python counts, per batch, the features present with at least `needed_values` values and orders descending. The two rank batches differently: on 200 generated cases with contiguous batch labels the orders agreed in 11, and in all 200 when R's missing-cell count is used instead, so the difference comes from the count. **Known difference.** -**Jaccard sort**: R uses pair-first-then-chain. Python uses nearest-neighbour chain. Different algorithms, but in practice jaccard and sparsity produce identical batch orderings across all tested configurations (5/10/20 batches, 20%/40% structural missingness). The algorithmic divergence has zero practical impact on output. **Will not be reworked to match R.** +**Jaccard sort**: R pairs the most similar batches first and then chains the pairs. Python builds a nearest-neighbour chain. The orders agreed in 54 of the same 200 cases. **Known difference.** -**Seriation sort**: R uses `seriation::seriate(binary_df, margin=2)` (hierarchical clustering + optimal leaf ordering). Python uses NumPy SVD on centred presence matrix, sort by PC1. Different mathematical approaches produce different orderings, but the impact on corrected values is <5% mean difference from no-sort baseline. The divergence is within the expected variation of different sorting heuristics. **Will not be reworked to match R.** +**Seriation sort**: R uses `seriation::seriate(binary_df, margin = 2)` (hierarchical clustering with optimal leaf ordering). Python orders batches by the first principal component of their presence vectors. The orders agreed in 24 of 400 cases. **Known difference.** + +Sorting changes the output only together with blocking. The orders are not changed to match R: no measurement shows that one gives better corrections than another. **Batch label renumbering**: R renumbers batch labels to 1,2,3... in first-appearance order after sort. Python keeps original IDs. Block structure is identical (boundaries detected by value change, not absolute label). @@ -106,15 +109,22 @@ R uses `plyr::rbind.fill` (align by row name). Python uses pre-allocated array + ## 4. Unique-Removal Algorithm: MINOR DIVERGENCE -R updates affiliation list in-place enabling chain rescues. Python pre-computes the non-unique target set from the original list, so rescued singletons do not become new targets in the same pass. This difference is now covered by dedicated `chain_rescue` fixtures for both `ur=True` and `ur=False`. +Both move a feature whose pattern is its own into the longest pattern of another feature that lies inside its own, including a pattern held by a single feature, which then keeps it. They differ in three ways: + +- HarmonizR walks the features in row order and takes the first of equally long candidates. HarmonizePy takes the features longest pattern first, and among equally long candidates the one more features hold, then the smallest, so the result does not depend on the row order. +- With no candidate, HarmonizR empties the feature's pattern, and the feature comes out missing. HarmonizePy leaves it unchanged, with its raw values. +- HarmonizePy never moves a feature into a pattern that spans a single batch, whose group is left raw anyway; HarmonizR does. + +For example, `(1,2,3,4), (1,2), (5,6), (5,6)` becomes `(1,2), (1,2), (5,6), (5,6)` in both. The `chain_rescue` fixtures cover both `ur=True` and `ur=False`. --- ## 5. Feature Retention Policy: INTENTIONAL DIVERGENCE -- **Single-feature group (1 feature, 2+ batches)**: R drops entirely. Python pass-through raw. +- **Single-feature group (1 feature, 2+ batches)**: R drops entirely. Python pass-through raw, with ComBat and with limma. +- **Feature with no value in a whole batch, engines called directly**: `sva::ComBat` 3.60.0 stops with a singular-matrix error, and `limma::removeBatchEffect` sets the coefficient it cannot estimate to zero. `combat()` and `remove_batch_effect()` fit such a feature on the batches it has: the unobserved batch is left out of its grand mean, of the batch priors, and of the limma contrasts. Because ComBat's batch priors are shared, such a feature also enters the priors of the batches it is observed in and moves the other features slightly. Both engines leave raw a feature with values in a single batch, and limma also a feature whose values do not outnumber its observed batches; with `ref_batch`, ComBat leaves raw a feature with no value in the reference batch. limma's level for such a feature is the unweighted mean of its observed batch means; R gives the same when an interior batch is missing, but a different level when the first or last batch is missing, because it sets the coefficients it cannot estimate to zero. `harmonize()` never sends such a feature to an engine, so its output is unaffected. +- **Constant feature in ComBat**: `sva::ComBat` 3.60.0 leaves out rows whose variance is exactly zero inside any batch with two or more samples, in every mode, and returns them raw. Its test uses `var()` without `na.rm`, so a row with a missing cell is never left out. Python leaves out, in every mode, a row whose pooled variance is below its 1e-12 floor (with `ref_batch`, the reference batch's variance), and in mode 1 also a row with a batch variance below 1e-12 of the pooled variance. The rule covers rows with missing cells and near-constant rows. A row that is constant in some batches only is corrected in modes 2 to 4: location-only mode never divides by one batch's variance, and in the non-parametric modes the floored batch gives the row no weight in the other features' priors. - **Single-batch block (2+ features, 1 batch)**: Both pass-through raw. -- **Feature with per-cell NaN**: R drops feature from output entirely. Python keeps as all-NaN row. - **Empty affiliation (no qualifying batches)**: R drops from rebuild. Python keeps as all-NaN. Python retains more features in all cases. The trade-off: retained features are not batch-corrected. @@ -124,10 +134,10 @@ Python retains more features in all cases. The trade-off: retained features are ## 6. Input/Output Differences - **TSV reader**: R uses `read.table(sep="\t", row.names=1, check.names=FALSE, comment.char="", stringsAsFactors=FALSE)`. Python uses `pd.read_csv(sep="\t", index_col=0)`. Same format. -- **Empty columns**: R uses `janitor::remove_empty(which=c("rows","cols"))` (removes both). Python uses `dropna(how="all", axis=0)` (rows only). R destroys empty columns; Python preserves. +- **Empty rows and columns**: R uses `janitor::remove_empty(which=c("rows","cols"))`, which removes both. Python keeps both: an empty row stays an all-missing row and an empty column stays in the output. - **Numeric coercion**: R uses `vapply(as.numeric)` which silently creates NA for non-numeric. Python uses pandas type inference and raises ValueError on non-numeric columns. R silently corrupts; Python rejects. -- **Duplicate rows**: R uses `unique(main_data)` on the full data frame (compares all columns). Python checks only the index. Different dedup scope. -- **Default output**: R writes `cured_data.tsv`. Python writes `_corrected.parquet` (or .tsv without pyarrow). +- **Duplicate rows**: R uses `unique(main_data)`, which compares values and ignores row names, so a feature whose values match another feature's is removed silently. Python removes a row only when its name and its values both repeat, logs the removal, and raises on a repeated name with different values. +- **Default output**: R writes `cured_data.tsv`. Python writes `_corrected.tsv` next to the input, or the extension of `--output-format`. - **Visualization**: R applies `2^` before plotting (assumes log2). Not supported in Python. - **S4 SummarizedExperiment**: R supports. Not applicable to Python. @@ -135,35 +145,43 @@ Python retains more features in all cases. The trade-off: retained features are ## 7. Verification Status -| Scenario | ComBat 1-4 | limma | Notes | -| --- | --- | --- | --- | -| Dense synthetic | PASS (rtol 2e-5 to 5e-4) | PASS (rtol 1e-9) | baseline fixture suite | -| Structural missingness | PASS (rtol 5e-4) | PASS (rtol 1e-8) | baseline fixture suite | -| Blocking (block=2,4) | PASS (rtol 5e-4) | PASS (rtol 1e-8) | fixture-backed | -| Sparsity sort + block | PASS (rtol 5e-4) | PASS (rtol 1e-8) | fixture-backed | -| Jaccard sort + block | PASS (rtol 5e-4) | -- | medium block=2 fixture plus broad unit coverage | -| Seriation sort + block | PASS (rtol 5e-4) | -- | medium block=2 fixture plus broad unit coverage | -| Per-cell NaN synthetic | PASS (max_rel 0.0000) | PASS (max_rel 0.0000) | NaN positions match | -| Murine unblocked | PASS (max_rel 0.0003) | PASS (max_rel 2e-10) | real data, NaN positions match | -| Murine blocked (block=2) | PASS (ComBat mode 1: max_rel 6e-06) | -- | benchmark wrapper bug fixed; blocked summary should still be regenerated | -| Unique-removal chain rescue | PASS (rtol 1e-4) | -- | dedicated `ur=True` and `ur=False` fixtures | -| Combined stress | PASS on value concordance for NaN-matching features | -- | dedicated fixture; minority NaN-position mismatch allowed | - -The catastrophic blocked benchmark rows previously reported in markdown and JSON artifacts were not real algorithmic divergences. The benchmark R wrapper passed `block` as an integer, HarmonizR rejected it, and the R side silently ran unblocked while Python still ran blocked. A corrected direct rerun on murine `ComBat` mode 1 with `block=2` gives `max_rel 5.73e-06`, `p95_rel 5.48e-15`, and `nan_match 1.0`. Treat existing benchmark-summary rows with `Block = 2` as invalid until they are regenerated with the fixed wrapper. +The tolerance each R concordance test asserts (rtol), or for the murine benchmark the largest relative difference found (max_rel); `--` means no R fixture. + +| Scenario | ComBat 1 to 4 | limma | +| --------------------------- | --------------------- | ------------------ | +| Dense synthetic | rtol 1e-6 to 5e-4 | rtol 1e-10 | +| Structural missingness | rtol 1e-5 to 5e-4 | rtol 1e-8 | +| Blocking (block 2, 4) | rtol 1e-5 to 5e-4 | rtol 1e-8 | +| Sparsity sort + block | rtol 1e-5 to 5e-4 | rtol 1e-8 | +| Jaccard sort + block | rtol 5e-4 (mode 1) | -- | +| Seriation sort + block | rtol 5e-4 (mode 1) | -- | +| Per-cell NaN synthetic | rtol 1e-8 to 1e-4 | rtol 1e-8 | +| Murine unblocked | max_rel 3e-4 | max_rel 2e-10 | +| Murine block 2 | max_rel 6e-6 (mode 1) | -- | +| Unique-removal chain rescue | rtol 1e-4 | -- | +| Combined stress | rtol 1e-4 | -- | + +- All scenarios pass. Missing cells must match except where noted. +- Jaccard and seriation have one `medium` block 2 fixture each, plus unit tests. +- Murine: missing cells match in modes 1 and 3 and limma; see section 1.1 for modes 2 and 4. +- Combined stress compares values on features whose missing cells match, and allows a minority to differ (sections 3 and 4). --- ## 8. Python-Only Improvements -- CLI with `--dry-run`, `--config`, `--summary`, `--json` +- A per-feature correction report (`return_report=True`, `--report`): each feature's status, the batches of its group, its group size, whether unique removal cropped it, and the repeats removed +- CLI with `--dry-run`, `--config`, `--summary`, `--json`, `--report` +- `InputScaleWarning` when the data do not look log-transformed +- Input checks that name the problem: infinite values, repeated sample names, repeated feature names with different values, and batch labels that are not whole numbers - Multiple output formats (TSV, CSV, Parquet) - `needed_values` exposed as user parameter - Shell tab-completion via `argcomplete` - Centralized input validation (`validation.py`) -- Parquet I/O (12x faster write than TSV) +- Parquet input and output - Self-contained seriation via NumPy SVD - Module-level logging -- Pre-allocated single-output-array rebuild (lower memory) +- Rebuild into one pre-allocated output array - Robust batch count via `len(unique())` ## 9. R-Only Features @@ -175,28 +193,32 @@ The catastrophic blocked benchmark rows previously reported in markdown and JSON --- -## 10. Complete Difference Inventory (26 Items) +## 10. Complete Difference Inventory (29 Items) ### Affects Output Values -1. **Single-feature groups**: R drops entirely. Python pass-through. Causes EB prior shift. -2. **Per-cell NaN in output**: R drops feature from output. Python keeps as all-NaN row. Cosmetic; same data loss. +1. **Single-feature groups**: R drops entirely. Python pass-through with either engine. Causes EB prior shift. +2. **Features returned missing**: in some modes R returns features entirely missing although the input has values (section 2.3). Python corrects them. 3. **Empty affiliation**: R drops from output entirely. Python keeps as all-NaN. -4. **Unique-removal chaining**: R updates in-place enabling chain rescues. Python uses static pre-computed set. R can rescue more singletons. +4. **Unique-removal order and empty targets**: R takes features in row order and empties a feature with no target; Python takes them longest pattern first, keeps such a feature raw, and never targets a one-batch pattern; see section 4. 5. **Jaccard sort**: pair-first-then-chain vs nearest-neighbour chain. Different orderings for 3+ batches. 6. **Seriation sort**: `seriation::seriate` vs SVD/PC1 projection. Different orderings. +7. **Sparsity sort**: R counts missing cells per batch; Python counts the features present with at least `needed_values` values. Orders agreed in 11 of 200 cases. +8. **Constant feature in ComBat**: R leaves out rows with zero variance in any batch, in every mode. Python leaves out rows whose variance its engine would floor, by the rules in section 5; in modes 2 to 4 a row constant in some batches only is corrected. +9. **Flat hyper-prior**: when a batch's scale estimates have zero variance across features, R's moment estimates of the inverse-gamma prior divide by zero. Python uses a flat prior, `(1, 1)`. ### Affects I/O or Robustness 1. **Batch label renumbering**: R renumbers after sort. Python keeps original IDs. No impact on block structure. 2. **Batch count**: R uses `tail()` (fragile). Python uses `len(unique())` (robust). -3. **Empty column removal**: R `janitor::remove_empty` removes both rows and cols. Python drops only all-NaN rows. + - **Description columns**: HarmonizR 1.10.0 reads the sample IDs from column 1 and the batches from column 3 by position, converting batches with `as.numeric`. Python uses the columns named `ID` and `batch` when present and falls back to those positions, and rejects batch labels that are not whole numbers. +3. **Empty rows and columns**: R `janitor::remove_empty` removes both. Python keeps both. 4. **Numeric coercion**: R `vapply(as.numeric)` silently creates NA. Python raises ValueError on non-numeric. -5. **Duplicate rows**: R `unique()` on full data frame. Python checks index only. Different dedup scope. +5. **Duplicate rows**: R `unique()` compares values only. Python requires the name and the values to repeat. 6. **Column name handling**: R `check.names=FALSE` preserves special chars. Python default may mangle them. Minor. 7. **Comment character**: R `comment.char=""` disables comment handling. Python default. No impact. 8. **String factors**: R `stringsAsFactors=FALSE`. Python no factor concept. R-only. -9. **Default output**: R `cured_data.tsv`. Python `_corrected.parquet`. Different. +9. **Default output**: R `cured_data.tsv`. HarmonizePy `_corrected.tsv` next to the input, or the extension of `--output-format`. ### Zero Impact on Output @@ -204,10 +226,10 @@ The catastrophic blocked benchmark rows previously reported in markdown and JSON 2. **Log-only counter**: R has `sum_counter` for console message only. Python omits. Never feeds algorithm. 3. **Visualization log2**: R applies `2^` before plotting. Python not supported. Purely diagnostic. 4. **S4 support**: R has SummarizedExperiment I/O. Not applicable to Python. -5. **Parallel execution**: R uses doParallel + foreach. Python single-threaded. Python faster anyway. +5. **Parallel execution**: R uses doParallel + foreach. HarmonizePy runs on one thread. 6. **Rebuild method**: R uses `rbind.fill`. Python uses pre-allocated array. Same output for same features. 7. **Diagnostic plotting**: R has boxplots. Not supported in Python. Purely cosmetic. 8. **var.pooled formula (dense)**: Both use `mean(residuals^2)`. Same. -9. **var.pooled formula (NaN)**: R uses `rowVars(residuals, na.rm=TRUE)`. Python uses `_row_var_nan`. Same ddof=1 formula. +9. **var.pooled formula (NaN)**: R uses `rowVars(residuals, na.rm=TRUE)`. Python uses `_row_var_nan_grouped`. Same ddof=1 formula. As in R, one missing cell anywhere switches every feature to this formula. 10. **NaN-safe `_it_sol`**: R handles per-feature NaN via `n()` in postvar. Python uses per-feature `n_per_gene`. Same approach. 11. **NaN-safe `_int_eprior`**: R uses `x <- sdat[i, !is.na(sdat[i, ])]`. Python uses per-gene non-NA count `n_i`. Same approach. diff --git a/benchmarks/RESULTS.md b/benchmarks/RESULTS.md index 388fc79..9d2deea 100644 --- a/benchmarks/RESULTS.md +++ b/benchmarks/RESULTS.md @@ -1,19 +1,18 @@ # Benchmark Results -This is the durable benchmark summary for the current HarmonizePy benchmark suite. It is intentionally more descriptive than the generated raw Markdown and JSON outputs. +Benchmark summary for HarmonizePy 0.4.0: runtime and memory of the Python implementation, and concordance with HarmonizR 1.10.0 on the datasets where an R baseline is practical. The raw outputs of a run go to `benchmarks/results/`, which is not tracked; rerun the commands below to reproduce them on your own hardware. -The raw `out` and `md` artifacts under `benchmarks/results/` are local run products from this machine. They are useful for ad hoc inspection, but they are not treated here as public, stable benchmark deliverables. If you want the raw benchmark outputs, rerun the commands below on your own hardware. +## How to reproduce -## How To Reproduce +The summary combines five runs. Each writes a fixed file under `benchmarks/results/`, and the figures command reads those files, so running the commands in order rebuilds every number and figure on this page. -The current summary combines two benchmark passes: - -- an R-backed parity pass over the representative validation datasets -- a Python-only extreme pass over the largest configured stress datasets +```bash +export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 -Reproduce them locally with: +# HarmonizR baselines, one R core (cached; the parity pass attaches them) +uv run python -m benchmarks.bench cache-r --datasets small medium dia murine scp_small --cores 1 -```bash +# Parity pass: Python against the cached R baselines uv run python -m benchmarks.bench run \ --datasets small medium dia murine scp_small \ --with-r --with-r-cores 1 \ @@ -21,210 +20,222 @@ uv run python -m benchmarks.bench run \ --out benchmarks/results/benchmark_r_parity.json \ --md benchmarks/results/benchmark_r_parity.md +# Python-only pass on the two largest datasets uv run python -m benchmarks.bench run \ --datasets large scp_large \ --n-reps 1 \ --no-warmup \ --out benchmarks/results/benchmark_python_extremes.json \ --md benchmarks/results/benchmark_python_extremes.md -``` - -Interpretation notes: - -- The parity pass uses cached HarmonizR baselines at 1 R core and includes concordance. -- The extreme pass is Python-only by design because those scales are not currently practical or reliable as HarmonizR parity baselines. -- The extreme pass uses a single timed repetition with no warmup so that the heaviest showcase runs remain tractable. - -## Benchmark Design - -The dataset mix is deliberate rather than exhaustive. The benchmark suite is trying to answer four separate questions: - -- Does HarmonizePy stay numerically aligned with HarmonizR on small and medium synthetic bulk workloads? -- Does that parity still hold on real matrices such as DIA proteomics and murine medulloblastoma data? -- Is there at least one R-backed SCP anchor, so the single-cell style regime is not omitted from parity checks? -- How does the Python implementation behave on stress-scale inputs where current HarmonizR baselines are not representative or do not complete reliably? - -That is why the suite keeps `small`, `medium`, `dia`, `murine`, and `scp_small` in the R-backed pass, while `large` and `scp_large` are showcased separately as Python-only runs. - -## Dataset Catalog - -`small` is the smallest synthetic bulk sanity check. It is `1000 x 20` with `5` batches and `30%` per-batch missingness. At `261 KB`, it is cheap to rerun and serves as the first correctness anchor for parity, blocking, and general pipeline behavior. - -`medium` is the main synthetic bulk workload. It is `5000 x 60` with `10` batches and `20%` per-batch missingness, and it includes both blocked and `sparsity`-sorted variants. At `4.3 MB`, it is still manageable enough for repeated parity work while being large enough to surface the current no-block parity gap. - -`large` is the synthetic bulk stress dataset. It is `10000 x 100` with `20` batches and `5%` per-batch missingness. At `16.7 MB`, it is used to show how blocking and sorting affect Python behavior at a materially larger scale. It is Python-only because the current HarmonizR baseline is not reliable enough here to make a fair parity claim. - -`murine` is the real murine medulloblastoma matrix. It is `4753 x 25` with `4` batches and no synthetic missingness injection. At `808 KB`, it provides a real-data checkpoint that is still small enough to keep the parity pass stable and repeatable. - -`dia` is the real DIA proteomics dataset. It is `8470 x 36` with `2` batches and CSV input files. At `4.8 MB`, it is an important real proteomics anchor, but it only appears in no-block scenarios because `block=2` would collapse into a degenerate single block for a two-batch design. - -`scp_small` is the smaller synthetic SCP cohort. It is `3000 x 1000` with `20` batches and `50%` abundance-pattern missingness. At `24.9 MB`, it gives the suite one R-backed SCP anchor so the parity story is not limited to bulk-style datasets. - -`scp_large` is the large SCP stress dataset. It is `5000 x 10000` with `100` batches and `60%` abundance-pattern missingness. At `375.5 MB`, it is the heaviest configured workload in the suite. It is intentionally Python-only because current HarmonizR runs do not finish reliably enough here, and the memory cost makes the R side a poor reference baseline. - -## Benchmark Environment - -These numbers were produced on the following machine and software stack. - -### System - -The benchmark machine was `Linux 6.17.9-76061709-generic` on an `AMD Ryzen 9 3950X 16-Core Processor` with `32` logical CPUs, `16` physical cores, `2` threads per core, `1` socket, and `125 GiB` of RAM. At the time of capture, about `95 GiB` was free and about `99 GiB` was available. - -The harness configuration reported Python at `1` process or thread, HarmonizR at `1` core for parity baselines, and system or BLAS threading at `32` threads. - -### Python stack - -The Python stack for the current `0.3.2` release documentation is Python `3.12.13` with NumPy `2.4.4`, pandas `3.0.2`, and HarmonizePy `0.3.2`. NumPy was linked against `scipy-openblas 0.3.31.188.0` with `DYNAMIC_ARCH`, `NO_AFFINITY`, and `MAX_THREADS=64`. NumPy reported `X86_V3` SIMD support on this machine. - -### R stack - -The R stack was R `4.6.0`, HarmonizR `1.10.0`, and Bioconductor `3.23`, with `doParallel 1.0.17`, `foreach 1.5.2`, `sva 3.60.0`, `limma 3.68.3`, and `BiocParallel 1.46.0`. R was linked against `/usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3`, with LAPACK from `/usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so`. - -## Why R Is Limited To One Core Here - -The current benchmark policy intentionally pins HarmonizR baselines to `1` R core. - -This is not because multi-core HarmonizR is conceptually unsupported. It is because the current `doParallel` plus `foreach` implementation interacts badly with multi-threaded OpenBLAS on Unix. Forked workers inherit the parent's BLAS thread pool, so increasing HarmonizR worker count can cause the workers to compete with BLAS threads instead of doing useful work. In practice that means worse wall-clock performance and much higher memory usage. - -The project's own investigation showed the pattern clearly: - -- the slowdown is a `doParallel(fork)` plus OpenBLAS oversubscription problem, not a correctness problem in HarmonizR -- the effect becomes worse on workloads that create many sub-matrices, especially blocked runs and higher missingness regimes -- memory usage rises sharply because each worker duplicates a large R process with loaded Bioconductor dependencies and matrix state - -That is why the current parity policy treats single-core HarmonizR as the fair and stable reference point. The large Python-only runs are also separated partly for that reason: once the R side becomes dominated by worker and BLAS interaction costs, the result stops being a useful numerical baseline and turns into a systems artifact. - -## R-Backed Parity Summary - -The R-backed parity cohort is: -- `small` -- `medium` -- `dia` -- `murine` -- `scp_small` +# Peak memory of both tools, each run in a fresh process -> memory_peak.json +uv run python -m benchmarks.memory_peak -Headline result: +# Scaling and blocking sweeps on synthetic matrices -> scaling.json +uv run python -m benchmarks.scaling -- Python is faster than single-core HarmonizR on every scenario in the parity pass. -- Concordance is excellent for `small`, `dia`, `scp_small`, and the blocked or blocked-plus-sorted `medium` scenarios. -- `murine` remains close to R, with the expected small differences on some mean-only and blocking paths. -- Unblocked `medium` is the one obvious parity outlier and should be read as a known caveat, not representative of the blocked pipeline. +# What each tool returns per feature, from the parity pass -> outcomes.json +uv run python -m benchmarks.outcomes -### Parity Speed Commentary - -The ratios are useful for scale, but the absolute runtime matters too. The table below keeps one representative row per dataset so the reader can see how long the comparison actually takes in both Python and R. - -| Dataset | Representative scenario | Python | R | Ratio context | Key point | -| --- | --- | --- | --- | --- | --- | -| `small` | `limma` | `0.0150s` | `1.007s` | `11.95x` to `67.13x` faster across the dataset | Python already has a large lead on the smallest matrix. | -| `dia` | `ComBat m3` | `1.7140s` | `456.024s` | `239.67x` to `266.06x` faster on non-parametric ComBat | Real proteomics still strongly favors Python. | -| `murine` | `ComBat m4 block=2` | `0.3656s` | `28.223s` | `5.98x` to `77.19x` faster across the dataset | Python stays ahead on both blocked and unblocked paths. | -| `medium` | `ComBat m2 block=2` | `0.0696s` | `5.361s` | `7.27x` to `77.03x` faster depending on mode and blocking | The blocked medium pipeline is especially efficient. | -| `scp_small` | `ComBat m1` | `1.0176s` | `54.932s` | `53.98x` to `286.20x` faster across the dataset | Python remains decisively ahead even on the smaller SCP workload. | - -### Parity Memory Commentary - -| Dataset | Python memory | R memory | Comment | -| --- | --- | --- | --- | -| `small` | below `1.05 MB` heap | not a concern at this scale | The smallest dataset is cheap on both sides. | -| `medium` | below `9.52 MB` heap | materially higher than Python | Blocking and sorting stay well within a modest Python footprint. | -| `murine` | below `7.26 MB` heap | higher than Python | Real data remains inexpensive on the Python side. | -| `dia` | `18.28 MB` to `31.18 MB` heap | up to about `368.5 MB` heap | Real proteomics shows a large Python memory advantage. | -| `scp_small` | about `74.13 MB` heap | up to about `380.8 MB` heap | This is the clearest SCP memory separation in the parity cohort. | - -Two `scp_small` Python scenarios showed growing repeated-run RSS tails: - -- `scp_small_ComBat_m1` -- `scp_small_ComBat_m4` - -That does not invalidate the benchmark, but it is the main memory-stability note worth retaining from the parity pass. - -### Concordance Commentary - -Strong parity regions: - -- `small` shows machine-precision or near-machine-precision concordance across the reported scenarios. -- `dia` is effectively exact across all reported scenarios. -- `scp_small` stays at machine-precision or near-machine-precision concordance. -- `medium` with `block=2` and `block=2, sort=sparsity` returns near-exact concordance with matching NaN structure. - -Important caveat: - -- `medium` without blocking is the clear anomaly in the current parity run. The worst row is `medium_ComBat_m3` with max relative difference `2.67e+01`, and the unblocked `medium` rows show NaN mismatch. - -Representative concordance points: - -| Scenario | Max relative difference | Interpretation | -| --- | --- | --- | -| `small_ComBat_m1` | `5.98e-06` | Near-exact parity. | -| `dia_ComBat_m3` | `5.12e-14` | Effectively exact. | -| `scp_small_ComBat_m1` | `7.04e-06` | Near-exact SCP parity at the smaller scale. | -| `medium_ComBat_m1_b2` | `7.39e-06` | Blocked medium remains near-exact. | -| `medium_ComBat_m3` | `2.67e+01` and NaN mismatch | This is the headline parity outlier. | - -The practical reading is simple: the blocked medium pipeline is in good shape, but the unblocked medium path is still the place where the parity story weakens and needs the most caution. - -## Python-Only Extreme Runs - -The Python-only extreme cohort is: - -- `large` -- `scp_large` - -These are not presented as R parity evidence. They are operational showcase runs for the largest configured workloads. - -### Extreme Speed Commentary - -Only Python seconds are shown here because these workloads are intentionally outside the current R-backed parity subset. - -| Scenario | Time | Comment | -| --- | --- | --- | -| `large_ComBat_m2_b2` | `0.7868s` | Fastest reported blocked bulk scenario in the extreme pass. | -| `large_limma` | `0.8957s` | Limma remains very competitive on `large`. | -| `large_ComBat_m1` | `6.5268s` | Unblocked parametric ComBat is much heavier than blocked `m2`. | -| `scp_large_limma` | `3.8705s` | Fastest SCP-large scenario. | -| `scp_large_ComBat_m1` | `9.2512s` | Slowest showcase scenario in the current extreme run. | - -Main points: - -- On `large`, blocking still helps materially. `ComBat m2` drops from `1.7190s` to `0.7868s` with `block=2`. -- On `scp_large`, `limma` is the fastest path at `3.8705s`. -- The slowest showcase scenario is `scp_large_ComBat_m1` at `9.2512s`. - -### Extreme Memory Commentary - -| Scenario | Python heap | Retained RSS delta | Comment | -| --- | --- | --- | --- | -| `large_ComBat_m1` | `46.65 MB` | `20428 KB` | `large` remains modest in memory terms. | -| `large_limma` | `33.67 MB` | `7332 KB` | Limma is lighter than ComBat on `large`. | -| `scp_large_limma` | `1170.88 MB` | `12416 KB` | SCP-large immediately pushes into gigabyte-scale memory use. | -| `scp_large_ComBat_m1` | `1262.97 MB` | `49416 KB` | Highest retained RSS delta in the showcase. | -| `scp_large_ComBat_m3` | `1252.55 MB` | `25612 KB` | Non-parametric SCP-large remains similarly memory heavy. | - -Main points: - -- `large` remains comfortably below `50 MB` Python heap in this run. -- `scp_large` is the real memory stress case. Python heap is roughly `1.17 GB` to `1.26 GB` depending on algorithm and mode. -- Because the extreme pass used one timed repetition, RSS stability is reported as `INSUFFICIENT-DATA` there by construction. - -## How To Read This Document - -Use the parity sections to answer: - -- how close HarmonizePy is to HarmonizR on the validated benchmark subset -- where NaN structure and shared-feature behavior remain aligned -- where the current parity caveat lives, namely unblocked `medium` - -Use the extreme section to answer: - -- what runtime to expect on the largest configured Python-only workloads -- how much blocking helps on `large` -- what memory envelope `scp_large` currently needs - -## Bottom Line +# Every figure, into benchmarks/figures/ and wiki/assets/ +uv run --group figures python -m benchmarks.figures +``` -- HarmonizePy is already strong on the R-backed benchmark subset, with Python faster than R across the board and excellent concordance outside the known unblocked `medium` outlier set. -- The benchmark design is intentional. It preserves real-data and SCP parity anchors while keeping the stress-scale runs useful rather than forcing weak or misleading R baselines. -- Single-core HarmonizR is used here because it is the stable reference on this stack. Multi-core HarmonizR currently competes with BLAS threads and inflates memory enough to distort the comparison. -- The Python-only extreme runs show that the implementation remains usable on `large` and `scp_large`, with `scp_large` serving as the main stress-test showcase for both runtime and memory. +- The R baselines and the peak-memory runs need R with the packages pinned by `renv.lock`; `memory_peak` keeps the measurements already in its file and adds the missing ones. +- The Python-only pass uses one timed repetition without warmup, so its memory stability is reported as `INSUFFICIENT-DATA` by construction. +- Python runs on one thread, with BLAS limited to one thread by the environment variables above. +- `benchmarks.figures` skips a figure whose result file is missing; `--help` lists the paths it reads. + +## Datasets + +| Dataset | Kind | Features | Samples | Batches | Missing | Size | R baseline | +| ----------- | ---------------------- | -------- | ------- | ------- | ------- | -------- | ---------- | +| `small` | Synthetic bulk | 1000 | 20 | 5 | 30% | 261 KB | yes | +| `medium` | Synthetic bulk | 5000 | 60 | 10 | 20% | 4.3 MB | yes | +| `large` | Synthetic bulk | 10000 | 100 | 20 | 5% | 16.7 MB | no | +| `murine` | Real (medulloblastoma) | 4753 | 25 | 4 | natural | 808 KB | yes | +| `dia` | Real (DIA proteomics) | 8470 | 36 | 2 | natural | 4.8 MB | yes | +| `scp_small` | Synthetic SCP | 3000 | 1000 | 20 | 50% | 24.9 MB | yes | +| `scp_large` | Synthetic SCP | 5000 | 10000 | 100 | 60% | 375.5 MB | no | + +- Missingness in the synthetic sets removes whole batches per feature (bulk) or follows a random detection profile per feature (SCP). +- `dia` has two batches, so it runs without blocking only; `block=2` would form a single block. +- `large` and `scp_large` have no R baseline; they show how the Python implementation scales. + +## Environment + +- A 16-core x86-64 desktop running Linux, shared with other work while the runs took place. +- Python 3.13.15, NumPy 2.5.4 with scipy-openblas 0.3.34, pandas 3.1.0, HarmonizePy 0.4.0. +- R baselines: R 4.6.2, HarmonizR 1.10.0, sva 3.60.0, limma 3.68.5, Bioconductor 3.23, as pinned by `renv.lock`, one core, on the same machine. +- The R baselines were cached immediately before the Python passes, so both columns saw the same load. + +HarmonizR runs on one core because its `doParallel` fork workers inherit the multi-threaded OpenBLAS pool and compete with its threads, so a multi-core timing would measure that interaction rather than the correction. Its per-scenario limit is 1800 s (`benchmarks/config.yaml`); `dia` ComBat 3 and 4 take about 310 s each. + +## Runtime + +

+ + + + Wall time of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy takes 21 ms to 2.0 s, HarmonizR 1.0 s to 312 s + +

+ +Wall time of `harmonize()` in seconds: the median of three repetitions for Python, on a matrix already in memory, and one run for R, whose time also includes reading its input file (at most 5% of its time on these datasets). + +| Scenario | Python (s) | R (s) | +| -------------------------- | ---------- | ----- | +| `small` limma | 0.021 | 1.06 | +| `small` ComBat 1 | 0.114 | 7.61 | +| `medium` ComBat 1 | 1.98 | 13.8 | +| `medium` ComBat 1, block 2 | 0.206 | 5.05 | +| `medium` ComBat 3, block 2 | 0.245 | 22.3 | +| `murine` ComBat 1 | 0.471 | 1.85 | +| `murine` ComBat 4, block 2 | 0.357 | 22.9 | +| `dia` ComBat 1 | 0.485 | 4.79 | +| `dia` ComBat 3 | 1.75 | 312 | +| `scp_small` limma | 0.169 | 57.1 | +| `scp_small` ComBat 1 | 0.709 | 58.5 | + +Python-only pass, one repetition: + +| Scenario | Python (s) | +| ------------------------- | ---------- | +| `large` limma | 0.431 | +| `large` ComBat 1 | 3.91 | +| `large` ComBat 2 | 1.11 | +| `large` ComBat 2, block 2 | 0.542 | +| `large` ComBat 3 | 6.96 | +| `large` ComBat 3, block 2 | 4.85 | +| `scp_large` limma | 2.17 | +| `scp_large` ComBat 1 | 4.17 | +| `scp_large` ComBat 3 | 4.74 | + +- Python was faster than single-core HarmonizR in every parity scenario, from about 4 times (`murine` ComBat 1) to about 340 times (`scp_small` limma). +- Blocking cuts the number of groups: on `medium` ComBat 1 it takes the run from 1.98 s to 0.206 s, and on `large` ComBat 2 from 1.11 s to 0.542 s. +- The non-parametric modes (3 and 4) compare each feature with every other feature in its group, so their cost grows with the square of the group size; they are the slowest modes on `dia`, `murine`, and `large`. + +## Scaling and blocking + +The sweeps in `scaling.json` correct synthetic matrices with ten batches, each feature absent from 20% of the batches, on one core, timing the median of three runs. + +

+ + + + Wall time of limma and the four ComBat modes as features grow from 1,000 to 50,000 at 60 samples, and as samples grow from 40 to 6,000 at 5,000 features + +

+ +| Matrix | Groups | limma (s) | ComBat 1 (s) | ComBat 3 (s) | +| -------------- | -----: | --------: | -----------: | -----------: | +| 1,000 x 60 | 185 | 0.109 | 0.924 | 0.807 | +| 50,000 x 60 | 761 | 0.665 | 4.49 | 8.55 | +| 5,000 x 40 | 389 | 0.223 | 1.95 | 1.68 | +| 5,000 x 6,000 | 413 | 1.50 | 3.82 | 3.62 | + +- The work follows the number of missingness groups, which grows far slower than the matrix: 50 times more features cost limma 6.1 times and ComBat 1 4.9 times the time, and 150 times more samples cost at most 6.7 times. +- The non-parametric modes compare each feature with every other feature of its group, so they overtake the parametric modes once groups get large (50,000 features). + +

+ + + + Wall time against the share of observed values kept, for limma, ComBat 1 and ComBat 3 at 5,000 and 20,000 features, without blocking and with block=2 + +

+ +- `block=2` joins neighbouring batches, so the 401 groups of the 5,000-feature matrix become 31; runs take 4 to 10 times less time, except ComBat 3 at 20,000 features (1.7 times less). +- The price is observed values: a feature missing from one batch of a block loses the whole block, so about 80% of the observed values reach the output instead of 99.7 to 99.9%. +- Without blocking, ComBat 1 and ComBat 3 take the same time at 20,000 features; the nested squares mark that point. + +## Memory + +### Against HarmonizR + +Peak resident memory of a fresh process that reads the data and description files, corrects the matrix once, and exits (`memory_peak.json`). This is the memory the operating system had to give each tool, interpreter and libraries included. HarmonizR runs on one core with BiocParallel set to serial, so all of its work stays in the measured process. + +

+ + + + Peak memory of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy 116 to 208 MB, HarmonizR 170 to 848 MB + +

+ +| Dataset | Python (MB) | R limma (MB) | R ComBat 1 (MB) | R ComBat 3 (MB) | +| ----------- | ----------: | -----------: | --------------: | --------------: | +| idle | 105 | 127 | 127 | 127 | +| `small` | 116 - 117 | 170 | 531 | 548 | +| `murine` | 122 - 123 | 193 | 543 | 667 | +| `medium` | 124 - 126 | 206 | 700 | 741 | +| `dia` | 139 - 142 | 199 | 621 | 734 | +| `scp_small` | 208 | 544 | 793 | 848 | + +- Python's column covers its three engines, which differ by at most 3 MB. Idle is each tool started, with its package loaded, and stopped. +- HarmonizePy needs 1.4 to 2.6 times less memory than HarmonizR with limma, and 3.8 to 5.9 times less with ComBat. +- Most of HarmonizR's ComBat peak is fixed: loading sva and its dependencies adds about 370 MB before any data is read. + +### Against input size + +

+ + + + Peak traced memory of one harmonize call against the size of the input matrix, from 0.5 MB to 229 MB, between 2.4 and 3.9 times the input + +

+ +Over the scaling sweep, the traced peak of one call stays between 2.4 and 3.9 times the input matrix as float64, from 0.5 MB to 229 MB of input; the five engines differ by at most a quarter. + +### Per call, in the parity pass + +Peak Python heap (tracemalloc) of one `harmonize()` call, against the R heap reported by `gc()`. + +| Dataset | Python min (MB) | Python max (MB) | R min (MB) | R max (MB) | +| ----------- | --------------- | --------------- | ---------- | ---------- | +| `small` | 0.7 | 1.4 | 69 | 355 | +| `medium` | 8.5 | 9.9 | 358 | 372 | +| `murine` | 4.5 | 6.3 | 370 | 371 | +| `dia` | 19.4 | 21.2 | 364 | 372 | +| `scp_small` | 70.7 | 73.6 | 393 | 393 | +| `large` | 33.8 | 46.3 | -- | -- | +| `scp_large` | 1171 | 1192 | -- | -- | + +- Minimum and maximum over the scenarios of each dataset; `--` means no R baseline. +- Python's retained RSS stayed flat across repetitions in every parity scenario. +- R runs every scenario in one process, so later R scenarios can reuse memory allocated by earlier ones. + +## Concordance with HarmonizR + +

+ + + + For each matrix with an R baseline, the share of input features each tool corrects, returns as measured, returns empty, or leaves out, with ComBat mode 1 + +

+ +Both tools correct the same features; HarmonizePy keeps a row for every feature it cannot correct, with its measured values or empty, where HarmonizR leaves such features out (`outcomes.json`, ComBat mode 1). + +Python against R on the features both outputs contain. Relative difference is `|py - r| / |r|` over cells where both have a value. "Python only" counts the features HarmonizePy returns and HarmonizR does not. + +| Scenario group | Max relative difference | Missing cells match | Python only | +| ------------------------------------------ | ----------------------- | ------------------- | ------------ | +| `small`, all modes | 6e-06 | yes | 1 | +| `small`, block 2 | 4e-06 | yes | 69 | +| `dia`, all modes | 5e-14 | yes | 0 | +| `scp_small` limma, ComBat 1 and 2 | 7e-06 | yes | 0 | +| `scp_small` ComBat 3 and 4 | 5e-15 | no | 0 | +| `murine` limma, ComBat 1 and 3 | 3e-04 | yes | 274 | +| `murine` ComBat 2 and 4 | 7e-09 | no | 229 | +| `murine` block 2 | 6e-06 | 1, 3 yes; 2, 4 no | 2222 to 2357 | +| `medium` block 2, with and without sorting | 7e-06 | yes | 38 | +| `medium` without blocking, all modes | 7.7 | no | 32 | + +- No feature appears only in HarmonizR's output in any scenario. +- ComBat mode 1 differs by up to 3e-04 relative (`murine`); its parametric solver stops at a convergence tolerance. The other modes differ by at most 7e-09. +- Python-only features are the ones HarmonizR drops: features alone in their group, features with no usable batch, and, with unique removal, features it empties because no target exists. HarmonizePy keeps them, raw or missing, and its correction report names each. +- `murine` ComBat 2 and 4: HarmonizR returns 870 features entirely missing although the input has values for them; HarmonizePy corrects them. Of the 229 features HarmonizR drops, 221 have values in a single batch and are kept raw, and 8 are empty rows. +- `medium` without blocking: the differences come from unique removal, where the two rules take features in a different order. HarmonizePy takes the longest affiliations first and HarmonizR takes rows in input order, so some features move to a different target, which also changes the groups they join. With limma, 49 of the 4968 shared features differ by more than 1e-4 relative or in their missing cells: 35 are features HarmonizePy cropped, 10 are in groups whose members those moves change, and 4 are features HarmonizePy keeps raw as alone in their pattern. With blocking there are fewer patterns and the outputs agree. The parity document describes the rule. +- `scp_small` ComBat 3 and 4: HarmonizR returns 1256 of the 3000 features entirely missing, although the input has values for them; HarmonizePy corrects them. On every cell both outputs have, the values agree to rounding. diff --git a/benchmarks/config.yaml b/benchmarks/config.yaml index 1aee1ed..4078218 100644 --- a/benchmarks/config.yaml +++ b/benchmarks/config.yaml @@ -107,7 +107,7 @@ datasets: # expand modes and yield one Scenario per (dataset, algorithm, mode, block, sort). # # All scenarios: unique_removal=True, needed_values=None (auto-derived by -# _bench.py: needed_values=2 for limma and ComBat modes 1,3; =1 for modes 2,4). +# harmonize(): needed_values=2 for limma and ComBat modes 1,3; =1 for modes 2,4). # ------------------------------------------------------------------------- scenario_matrix: bulk: # limma + ComBat m1-4 plain, plus ComBat m1-4 with block=2 @@ -134,7 +134,7 @@ scenario_matrix: r_cache: cores_variants: [1, 16] # both cached; each is an independent cache entry default_cores: 1 # which variant --with-r / --with-r-cores uses by default - timeout_s: 300 # per-scenario hard limit inside R withTimeout() + timeout_s: 1800 # per-scenario hard limit inside R withTimeout(); dia ComBat 3 and 4 need over 300 s # Note: withTimeout() comes from the R.utils package. benchmark_r.R must # load R.utils before the scenario loop. diff --git a/benchmarks/datasets.py b/benchmarks/datasets.py index 1028f17..7272347 100644 --- a/benchmarks/datasets.py +++ b/benchmarks/datasets.py @@ -1,7 +1,6 @@ """Dataset definitions, generation, and path resolution for benchmarks. -Absorbs the data generation logic from the old ``generate_data.py`` and -adds a lookup layer that resolves dataset short names to file paths +Generates the synthetic datasets, and resolves dataset short names to file paths using the config.yaml ``datasets`` section. Usage:: diff --git a/benchmarks/figures.py b/benchmarks/figures.py new file mode 100644 index 0000000..f1a9845 --- /dev/null +++ b/benchmarks/figures.py @@ -0,0 +1,982 @@ +"""Benchmark figures, light and dark, from the JSON the benchmark runs write. + + uv run --group figures python -m benchmarks.figures + +reads the result files under ``benchmarks/results/`` at the names the +commands in ``benchmarks/RESULTS.md`` give them, and writes each figure as an +SVG and a PNG (200 dpi on the theme's page color, 256 colors, no dithering) +to ``benchmarks/figures/``, with a copy of the PNG in ``wiki/assets/``: + +- ``01-speed``: wall time of both tools per dataset and engine (parity pass). +- ``02-memory``: peak memory of both tools in a fresh process (memory_peak). +- ``03-scaling``: wall time against features and samples (scaling). +- ``04-memory-scaling``: peak memory against the input size (scaling). +- ``05-blocking``: what ``block=2`` saves in time and costs in kept values (scaling). +- ``06-outcomes``: what each tool returns for every input feature (outcomes). + +A figure whose result file is missing is skipped. + +Colors: HarmonizePy as the subject (teal on the light page, Python yellow on +the dark one) against a recessive gray for HarmonizR; the engines as three hues +(limma, parametric ComBat, non-parametric ComBat). Every pair was checked for +color vision deficiency separation and contrast on both page colors. +""" + +from __future__ import annotations + +import argparse +import io +import json +import math +import textwrap +from pathlib import Path +from typing import Any + +import matplotlib + +matplotlib.use("svg") +import matplotlib.pyplot as plt +from matplotlib.colors import to_rgb +from matplotlib.lines import Line2D +from matplotlib.patches import Patch +from matplotlib.ticker import FixedLocator, FuncFormatter, LogLocator, NullFormatter, NullLocator +from PIL import Image + +plt.rcParams.update({"font.family": "DejaVu Sans", "svg.hashsalt": "harmonizepy"}) + +# GitHub's page colors, with the HarmonizePy logo teal as the accent. +THEMES: dict[str, dict[str, str]] = { + "light": { + "bg": "#ffffff", + "ink": "#1f2328", + "ink2": "#59636e", + "muted": "#818b98", + "grid": "#d1d9e0", + "region": "#e6f4f2", + "subject": "#0A7A6F", + "other": "#8c959f", + "limma": "#2a78d6", + "parametric": "#eb6834", + "nonparametric": "#1baf7a", + }, + "dark": { + "bg": "#0d1117", + "ink": "#f0f6fc", + "ink2": "#9198a1", + "muted": "#656c76", + "grid": "#3d444d", + "region": "#2a2410", + "subject": "#FFD43B", + "other": "#6e7681", + "limma": "#3987e5", + "parametric": "#d95926", + "nonparametric": "#199e70", + }, +} +SUBJECT, OTHER = "HarmonizePy", "HarmonizR" +DATASETS = ("small", "medium", "murine", "dia", "scp_small") +DATASET_LABEL = { + "small": "small", + "medium": "medium", + "murine": "murine", + "dia": "dia", + "scp_small": "scp_small", + "large": "large", + "scp_large": "scp_large", +} +# The engines, in legend order: (algorithm, mode) -> (label, color key, dashed). +ENGINES: dict[tuple[str, int | None], tuple[str, str, bool]] = { + ("limma", None): ("limma", "limma", False), + ("ComBat", 1): ("ComBat 1, parametric", "parametric", False), + ("ComBat", 2): ("ComBat 2, parametric, location only", "parametric", True), + ("ComBat", 3): ("ComBat 3, non-parametric", "nonparametric", False), + ("ComBat", 4): ("ComBat 4, non-parametric, location only", "nonparametric", True), +} +MARKER = { + ("limma", None): "o", + ("ComBat", 1): "s", + ("ComBat", 2): "s", + ("ComBat", 3): "D", + ("ComBat", 4): "D", +} + + +def times(r: float) -> str: + """A ratio as a short multiple: 0.62x, 1.4x, 24x, 310x.""" + if r >= 100: + return f"{r:.0f}x" + if r >= 10: + return f"{r:.0f}x" + if r >= 0.995: + return f"{r:.1f}x" + return f"{r:.2g}x" + + +def seconds(s: float) -> str: + """A wall time: 21 ms, 0.47 s, 5.0 s, 312 s.""" + if s < 0.1: + return f"{s * 1000:.0f} ms" + if s < 10: + return f"{s:.2g} s" if s < 1 else f"{s:.1f} s" + return f"{s:.0f} s" + + +def log_axis(axis: Any, fmt: Any, subs: tuple[float, ...] = (1.0, 2.0, 5.0)) -> None: + axis.set_major_locator(LogLocator(base=10, subs=subs)) + axis.set_major_formatter(FuncFormatter(fmt)) + axis.set_minor_formatter(NullFormatter()) + axis.set_minor_locator(NullLocator()) + + +def count_fmt(v: float, _: Any = None) -> str: + for div, suffix in ((1e6, "M"), (1e3, "k")): + if v >= div: + return f"{v / div:g}{suffix}" + return f"{v:g}" + + +def decades(axis: Any) -> None: + """Every third power of ten, as 10^-15 ... 1, without minor ticks.""" + axis.set_major_locator(FixedLocator([10.0**k for k in range(-15, 1, 3)])) + axis.set_major_formatter( + FuncFormatter(lambda v, _: "1" if v == 1 else f"$10^{{{math.log10(v):.0f}}}$") + ) + axis.set_minor_locator(NullLocator()) + + +def spread_log(values: list[float], gap: float) -> list[float]: + """Label heights for points at `values` (log scale), at least `gap` decades apart, in input order.""" + order = sorted(range(len(values)), key=lambda i: values[i]) + placed = [0.0] * len(values) + last = -math.inf + for i in order: + y = max(math.log10(values[i]), last + gap) + placed[i] = 10**y + last = y + return placed + + +def engine_key(scenario: dict[str, Any]) -> tuple[str, int | None]: + return ( + scenario["algorithm"], + scenario.get("combat_mode") if scenario["algorithm"] == "ComBat" else None, + ) + + +RESULTS = "benchmarks/results" + + +class Figures: + def __init__( + self, + parity: dict[str, Any], + scaling: dict[str, Any] | None, + outcomes: dict[str, Any] | None, + out: Path, + memory_peak: dict[str, Any] | None = None, + wiki: Path | None = None, + ) -> None: + self.memory_peak = memory_peak + self.wiki = wiki + self.parity = parity["results"] + self.scaling = scaling + self.outcomes = outcomes + self.system = parity["system"] + self.datasets = parity["datasets"] + self.out = out + out.mkdir(parents=True, exist_ok=True) + + # ---- shared layout --------------------------------------------------------- + + def axes( + self, theme: str, ncols: int, width: float, height: float, sharey: bool = False + ) -> tuple[Any, list[Any]]: + t = THEMES[theme] + fig, axes = plt.subplots(1, ncols, figsize=(width, height), sharey=sharey, squeeze=False) + fig.patch.set_facecolor(t["bg"]) + for ax in axes[0]: + ax.set_facecolor(t["bg"]) + for side in ("top", "right"): + ax.spines[side].set_visible(False) + for side in ("left", "bottom"): + ax.spines[side].set_color(t["muted"]) + ax.tick_params(colors=t["ink2"], labelsize=8.5, length=3) + ax.grid(True, which="major", color=t["grid"], linewidth=0.6, alpha=0.8) + ax.set_axisbelow(True) + return fig, list(axes[0]) + + def panel(self, ax: Any, theme: str, title: str, xlabel: str, ylabel: str = "") -> None: + t = THEMES[theme] + ax.set_title(title, loc="left", fontsize=10, color=t["ink"], fontweight="bold", pad=8) + ax.set_xlabel(xlabel, fontsize=8.5, color=t["ink2"]) + if ylabel: + ax.set_ylabel(ylabel, fontsize=8.5, color=t["ink2"]) + + def finish( + self, + fig: Any, + stem: str, + theme: str, + title: str, + subtitle: str, + handles: list[Any] | None = None, + ncol: int | None = None, + ) -> None: + """Title and italic note centered on top, legend centered below, tight bounds.""" + t = THEMES[theme] + fig.tight_layout(w_pad=2.0) + boxes = [ax.get_tightbbox() for ax in fig.axes] + fh = fig.bbox.height + top = max(b.y1 for b in boxes) / fh + bottom = min(b.y0 for b in boxes) / fh + inch = 1 / fig.get_figheight() + lines = textwrap.wrap(subtitle, int(fig.get_figwidth() * 15)) + fig.text( + 0.5, + top + 0.16 * inch, + "\n".join(lines), + ha="center", + va="bottom", + fontsize=9, + color=t["ink2"], + style="italic", + linespacing=1.45, + ) + fig.text( + 0.5, + top + (0.26 + 0.2 * len(lines)) * inch, + title, + ha="center", + va="bottom", + fontsize=13, + color=t["ink"], + fontweight="bold", + ) + if handles: + fig.legend( + handles=handles, + loc="upper center", + bbox_to_anchor=(0.5, bottom - 0.06 * inch), + ncol=ncol or min(len(handles), 5), + frameon=False, + fontsize=8.5, + labelcolor=t["ink"], + handlelength=2.2, + columnspacing=1.5, + borderaxespad=0, + ) + path = self.out / f"{stem}-{theme}.svg" + fig.savefig(path, format="svg", facecolor=t["bg"], bbox_inches="tight", pad_inches=0.2) + # The README's copy: a flat chart needs few colors, so a 256-color + # palette without dithering keeps every edge and keeps the file small. + buf = io.BytesIO() + fig.savefig( + buf, format="png", dpi=200, facecolor=t["bg"], bbox_inches="tight", pad_inches=0.2 + ) + image = ( + Image.open(buf) + .convert("RGB") + .quantize(256, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE) + ) + image.save(path.with_suffix(".png"), format="png", optimize=True) + if self.wiki is not None: + # The wiki names its images by subject: 01-speed-light.png -> benchmark-speed-light.png. + image.save(self.wiki / f"benchmark-{stem[3:]}-{theme}.png", format="png", optimize=True) + plt.close(fig) + + def engine_handles(self, theme: str, engines: list[tuple[str, int | None]]) -> list[Any]: + t = THEMES[theme] + handles = [] + for key in engines: + label, color, dashed = ENGINES[key] + handles.append( + Line2D( + [], + [], + color=t[color], + linewidth=1.8, + linestyle=(0, (4, 2)) if dashed else "-", + marker=MARKER[key], + markersize=6, + markerfacecolor=t["bg"] if dashed else t[color], + markeredgecolor=t[color], + markeredgewidth=1.4, + label=label, + ) + ) + return handles + + # ---- 01, 02: speed and memory against HarmonizR ---------------------------------------- + + PANELS = (("limma", None), ("ComBat", 1), ("ComBat", 3)) + PANEL_TITLES = ("limma", "ComBat, parametric (mode 1)", "ComBat, non-parametric (mode 3)") + + def paired( + self, + theme: str, + stem: str, + values: dict[tuple[str, Any], tuple[float, float]], + *, + fmt: Any, + gap: Any, + ticks: list[float], + xlim: tuple[float, float], + xlabel: str, + title: str, + note: str, + baselines: tuple[float, float] | None = None, + ) -> None: + """Both tools per dataset on one log axis, one panel per engine: the shared headline layout.""" + t = THEMES[theme] + meta = self.datasets + order = sorted(DATASETS, key=lambda d: meta[d]["features"] * meta[d]["samples"]) + fig, axes = self.axes(theme, 3, 12, 0.62 * len(order) + 1.3, sharey=True) + ys = list(range(len(order)))[::-1] + # A page-colored box behind each label, so grid and idle lines pass behind the text. + label_box = {"boxstyle": "square,pad=0.15", "facecolor": t["bg"], "edgecolor": "none"} + for ax, key, panel_title in zip(axes, self.PANELS, self.PANEL_TITLES, strict=True): + if baselines: + for value, color in zip(baselines, (t["subject"], t["other"]), strict=True): + ax.axvline(value, color=color, linewidth=1.0, linestyle=(0, (1, 2)), zorder=0) + for y, ds in zip(ys, order, strict=True): + py, r = values[(ds, key)] + ax.plot( + [py, r], + [y, y], + color=t["region"], + linewidth=7, + solid_capstyle="round", + zorder=1, + ) + ax.plot( + r, + y, + "o", + markersize=7.5, + markerfacecolor=t["bg"], + markeredgecolor=t["other"], + markeredgewidth=1.6, + zorder=3, + ) + ax.plot(py, y, "o", markersize=7.5, color=t["subject"], zorder=4) + left, right = (py, r) if py <= r else (r, py) + ax.annotate( + fmt(left), + (left, y), + xytext=(-8, 0), + textcoords="offset points", + bbox=label_box, + ha="right", + va="center", + fontsize=7.8, + color=t["ink"] if left == py else t["ink2"], + fontweight="bold" if left == py else "normal", + ) + ax.annotate( + fmt(right), + (right, y), + xytext=(8, 0), + textcoords="offset points", + bbox=label_box, + ha="left", + va="center", + fontsize=7.8, + color=t["ink"] if right == py else t["ink2"], + fontweight="bold" if right == py else "normal", + ) + ax.annotate( + gap(py, r), + (math.sqrt(py * r), y), + xytext=(0, 8), + textcoords="offset points", + bbox=label_box, + ha="center", + va="bottom", + fontsize=7, + color=t["ink2"], + ) + ax.set_xscale("log") + ax.set_xlim(*xlim) + ax.xaxis.set_major_locator(FixedLocator(ticks)) + ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: fmt(v))) + ax.xaxis.set_minor_locator(NullLocator()) + ax.grid(False, axis="y") + ax.tick_params(axis="y", length=0, pad=10) + ax.set_ylim(-0.6, len(order) - 0.4) + self.panel(ax, theme, panel_title, xlabel) + axes[0].set_yticks(ys) + axes[0].set_yticklabels( + [ + f"{ds}\n{meta[ds]['features']:,} x {meta[ds]['samples']:,}, {meta[ds]['batches']} batches" + for ds in order + ], + fontsize=8.6, + color=t["ink"], + linespacing=1.5, + ) + handles = [ + Line2D( + [], + [], + marker="o", + linestyle="none", + markersize=7.5, + color=t["subject"], + label=SUBJECT, + ), + Line2D( + [], + [], + marker="o", + linestyle="none", + markersize=7.5, + markerfacecolor=t["bg"], + markeredgecolor=t["other"], + markeredgewidth=1.6, + label=f"{OTHER} 1.10.0", + ), + ] + if baselines: + handles += [ + Line2D( + [], + [], + color=t["subject"], + linewidth=1.0, + linestyle=(0, (1, 2)), + label=f"{SUBJECT} idle, {fmt(baselines[0])}", + ), + Line2D( + [], + [], + color=t["other"], + linewidth=1.0, + linestyle=(0, (1, 2)), + label=f"{OTHER} idle, {fmt(baselines[1])}", + ), + ] + self.finish(fig, stem, theme, title, note, handles, ncol=len(handles)) + + def headline(self, theme: str) -> None: + """Wall time of both tools per dataset, in seconds, one panel per engine family.""" + values = {} + for e in self.parity: + s = e["scenario"] + if not s.get("block") and e.get("r") and e["r"].get("median_s"): + values[(s["dataset"], engine_key(s))] = ( + e["python"]["median_s"], + e["r"]["median_s"], + ) + self.paired( + theme, + "01-speed", + values, + fmt=seconds, + gap=lambda py, r: times(r / py) + " faster", + ticks=[0.01, 0.1, 1, 10, 100, 1000], + xlim=(0.0015, 2500), + xlabel="wall time, log scale", + title="The same correction in a fraction of the time", + note="Wall time of one correction on the same matrix, both on one core: HarmonizePy the median " + "of three runs on a matrix already in memory, HarmonizR one run that also reads its input " + "file (at most 5% of its time here). Rows run from the smallest matrix to the largest " + "(features x samples); how closely the outputs agree is in RESULTS.md.", + ) + + def memory_headline(self, theme: str) -> None: + """Peak memory of both tools per dataset, each run in its own process.""" + mp = self.memory_peak + values = { + (r["dataset"], (r["algorithm"], r["mode"])): ( + r["harmonizepy"]["peak_mb"], + r["harmonizr"]["peak_mb"], + ) + for r in mp["results"] + } + base = (mp["baseline_mb"]["harmonizepy"], mp["baseline_mb"]["harmonizr"]) + + def gap(py: float, r: float) -> str: + return f"{times(r / py)} less" if r >= py else f"{times(py / r)} more" + + self.paired( + theme, + "02-memory", + values, + fmt=lambda v: "1 GB" if v == 1000 else f"{v:,.0f} MB", + gap=gap, + ticks=[50, 100, 200, 500, 1000], + xlim=(38, 1700), + xlabel="peak memory of the process, log scale", + title="The same correction in less memory", + note="Peak resident memory of a fresh process that reads both input files, corrects the " + "matrix once and exits; HarmonizR on one core with BiocParallel serial, so all of its work is " + "measured. Dotted lines: each tool started and left idle. Loading sva adds about 370 MB to " + "HarmonizR's ComBat runs before any data is read.", + baselines=base, + ) + + # ---- 03: scaling --------------------------------------------------------------- + + def scaling_figure(self, theme: str) -> None: + """Wall time against features and against samples, with the groups each matrix forms.""" + t = THEMES[theme] + sc = self.scaling + design = sc["design"] + fig, axes = self.axes(theme, 2, 12, 5.0, sharey=True) + sweeps = ( + ( + "features", + "n_features", + f"More features ({design['feature_sweep_samples']} samples)", + "features", + ), + ( + "samples", + "n_samples", + f"More samples ({design['sample_sweep_features']:,} features)", + "samples", + ), + ) + for ax, (part, xkey, title, unit) in zip(axes, sweeps, strict=True): + ends: list[tuple[float, float]] = [] + for key, (_label, color, dashed) in ENGINES.items(): + pts = sorted( + (r[xkey], r["median_s"]) for r in sc[part] if (r["algorithm"], r["mode"]) == key + ) + xs, ys = zip(*pts, strict=True) + ax.plot( + xs, + ys, + color=t[color], + linewidth=1.8, + linestyle=(0, (4, 2)) if dashed else "-", + marker=MARKER[key], + markersize=5.5, + markerfacecolor=t["bg"] if dashed else t[color], + markeredgecolor=t[color], + markeredgewidth=1.3, + zorder=3, + ) + ends.append((xs[-1], ys[-1])) + for (x, y), ly in zip(ends, spread_log([y for _, y in ends], 0.075), strict=True): + ax.annotate( + seconds(y), + (x, y), + xytext=(x * 1.12, ly), + textcoords="data", + va="center", + fontsize=7.4, + color=t["ink"], + ) + # The affiliation groups each matrix forms, the same for every engine at a given size. + groups = sorted( + {(r[xkey], r["n_groups"]) for r in sc[part] if r["algorithm"] == "limma"} + ) + for x, g in groups: + ax.annotate( + f"{g}", + (x, 0), + xycoords=("data", "axes fraction"), + xytext=(0, 6), + textcoords="offset points", + ha="center", + fontsize=7.2, + color=t["ink2"], + ) + ax.annotate( + "groups:", + (groups[0][0], 0), + xycoords=("data", "axes fraction"), + xytext=(-14, 6), + textcoords="offset points", + ha="right", + fontsize=7.2, + color=t["ink2"], + ) + ax.set_xscale("log") + ax.set_yscale("log") + log_axis(ax.xaxis, count_fmt) + ax.set_xlim(groups[0][0] / 1.6, groups[-1][0] * 2.2) + ax.set_ylim(0.03, 30) + ax.yaxis.set_major_locator(FixedLocator([0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 20])) + ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: seconds(v))) + ax.yaxis.set_minor_locator(NullLocator()) + self.panel( + ax, + theme, + title, + f"{unit}, log scale", + "wall time, log scale" if part == "features" else "", + ) + self.finish( + fig, + "03-scaling", + theme, + "Time grows far slower than the matrix", + f"Synthetic matrices, {design['n_batches']} batches, {design['missing_frac']:.0%} of features " + "absent from each batch, one core, median of three runs. Fifty times more features costs limma and " + "parametric ComBat five to six times the time, and 150 times more samples at most seven: the work follows the number of " + "missingness groups (numbers along the bottom), which grows slowly. The non-parametric modes " + "rise once groups get large, as each feature is weighed against every other in its group.", + self.engine_handles(theme, list(ENGINES)), + ncol=3, + ) + + # ---- 04: memory against size ---------------------------------------------------------------- + + def memory(self, theme: str) -> None: + """Peak memory of one call against the size of its input matrix, one point per matrix.""" + t = THEMES[theme] + fig, (ax,) = self.axes(theme, 1, 8.0, 5.4) + lo, hi = 0.25, 600 + for k in (1, 3, 10): + ax.plot( + [lo, hi], + [lo * k, hi * k], + color=t["muted"], + linewidth=0.9, + linestyle=(0, (2, 3)), + zorder=1, + ) + # Labels sit below the top of the plot, where the steepest line leaves it. + xr = min(hi, 1000 / k) + ax.annotate( + f"{k}x the input", + (xr, xr * k), + xytext=(-4, 4), + textcoords="offset points", + ha="right", + va="bottom", + fontsize=7.6, + color=t["ink2"], + rotation=33, + rotation_mode="anchor", + ) + ratios = [] + for part, marker in (("features", "o"), ("samples", "s")): + by_matrix: dict[float, list[float]] = {} + for r in self.scaling[part]: + by_matrix.setdefault(r["input_mb"], []).append(r["peak_mb"]) + for x, peaks in sorted(by_matrix.items()): + ratios += [p / x for p in peaks] + ax.plot( + [x, x], [min(peaks), max(peaks)], color=t["subject"], linewidth=1.2, zorder=2 + ) + ax.plot( + x, + max(peaks), + marker, + markersize=7, + color=t["subject"], + markerfacecolor=t["subject"] if marker == "o" else t["bg"], + markeredgewidth=1.5, + zorder=3, + ) + ax.set_xscale("log") + ax.set_yscale("log") + ax.set_xlim(lo, hi) + ax.set_ylim(lo, 2500) + for axis in (ax.xaxis, ax.yaxis): + axis.set_major_locator( + FixedLocator([0.5, 1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000]) + ) + axis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:g} MB")) + axis.set_minor_locator(NullLocator()) + self.panel( + ax, + theme, + "Peak memory against input size", + "input matrix as float64, log scale", + "peak memory of one call, log scale", + ) + handles = [ + Line2D( + [], + [], + marker="o", + linestyle="none", + markersize=7, + color=t["subject"], + label="more features, 60 samples", + ), + Line2D( + [], + [], + marker="s", + linestyle="none", + markersize=7, + markerfacecolor=t["bg"], + markeredgecolor=t["subject"], + markeredgewidth=1.5, + label="more samples, 5,000 features", + ), + ] + self.finish( + fig, + "04-memory-scaling", + theme, + f"Peak memory is {min(ratios):.1f} to {max(ratios):.1f} times the input", + "Every matrix of the scaling sweep, from 0.5 MB to 229 MB of input. Peak memory is Python's " + "traced peak during harmonize() plus the output array. The mark is the highest of the five " + "engines and the bar under it reaches the lowest; they differ by at most a quarter.", + handles, + ncol=2, + ) + + # ---- 05: blocking ---------------------------------------------------------------- + + def blocking(self, theme: str) -> None: + """Time against observed values kept, each run without and with block=2.""" + t = THEMES[theme] + recs = self.scaling["blocking"] + fig, (ax,) = self.axes(theme, 1, 8.0, 5.0) + sizes = sorted({r["n_features"] for r in recs}) + size_marker = dict(zip(sizes, ("o", "s"), strict=False)) + drawn: dict[tuple[str, float], list[float]] = {} + for a in (r for r in recs if r["block"] is None): + b = next( + r + for r in recs + if r["block"] == 2 + and r["n_features"] == a["n_features"] + and (r["algorithm"], r["mode"]) == (a["algorithm"], a["mode"]) + ) + key = (a["algorithm"], a["mode"]) + color = t[ENGINES[key][1]] + xa, xb = ( + 100 * a["observed_out"] / a["observed_in"], + 100 * b["observed_out"] / b["observed_in"], + ) + ax.annotate( + "", + (xb, b["median_s"]), + (xa, a["median_s"]), + arrowprops={ + "arrowstyle": "-|>", + "color": color, + "linewidth": 1.4, + "shrinkA": 6, + "shrinkB": 6, + "mutation_scale": 11, + }, + ) + m = size_marker[a["n_features"]] + # Two engines can take the same time on the same matrix; the later one is + # drawn larger behind the first, so both outlines stay visible. + spot = (m, round(xa, 1)) + nested = any(abs(math.log(a["median_s"] / s)) < 0.05 for s in drawn.get(spot, [])) + drawn.setdefault(spot, []).append(a["median_s"]) + ax.plot( + xa, + a["median_s"], + m, + markersize=10.5 if nested else 7, + markerfacecolor=t["bg"], + markeredgecolor=color, + markeredgewidth=1.5, + zorder=2.5 if nested else 3, + ) + ax.plot(xb, b["median_s"], m, markersize=7, color=color, zorder=3) + ax.set_yscale("log") + ax.set_xlim(76, 101.5) + ax.set_ylim(0.025, 6) + ax.yaxis.set_major_locator(FixedLocator([0.05, 0.1, 0.2, 0.5, 1, 2, 5])) + ax.yaxis.set_major_formatter(FuncFormatter(lambda v, _: seconds(v))) + ax.yaxis.set_minor_locator(NullLocator()) + ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:g}%")) + g = { + r["block"]: r["n_groups"] + for r in recs + if r["n_features"] == sizes[0] and r["algorithm"] == "limma" + } + self.panel( + ax, + theme, + "Each run without blocking, and with block=2", + "observed input values that reach the output", + "wall time, log scale", + ) + handles = [ + Line2D([], [], color=t["limma"], linewidth=1.8, label="limma"), + Line2D([], [], color=t["parametric"], linewidth=1.8, label="ComBat 1, parametric"), + Line2D( + [], [], color=t["nonparametric"], linewidth=1.8, label="ComBat 3, non-parametric" + ), + *[ + Line2D( + [], + [], + marker=size_marker[s], + linestyle="none", + markersize=7, + markerfacecolor=t["bg"], + markeredgecolor=t["ink2"], + markeredgewidth=1.4, + label=f"{s:,} features", + ) + for s in sizes + ], + ] + self.finish( + fig, + "05-blocking", + theme, + "Blocking buys speed with observed values", + f"block=2 joins neighbouring batches, so {g[None]} missingness groups become {g[2]} and a run " + "takes a fraction of the time; a feature missing from one batch of a block loses the whole " + "block, so fewer of its observed values reach the output. Arrows run from each batch its own " + f"block (hollow) to block=2 (filled). Synthetic matrices, {self.scaling['design']['n_batches']} " + "batches, 60 samples.", + handles, + ncol=5, + ) + + # ---- 06: what each tool returns per feature -------------------------------------------- + + def outcomes_figure(self, theme: str) -> None: + """Share of input features each tool corrects, returns raw, returns empty, or drops.""" + t = THEMES[theme] + rows = sorted(self.outcomes["datasets"], key=lambda r: DATASETS.index(r["dataset"])) + classes = ( + ("corrected", "corrected", mix(t["ink"], t["bg"], 0.78), None), + ("raw", "returned as measured", mix(t["ink"], t["bg"], 0.45), None), + ("empty", "returned empty", mix(t["ink"], t["bg"], 0.18), None), + ("dropped", "left out of the output", t["bg"], "////"), + ) + fig, (ax,) = self.axes(theme, 1, 11, 0.95 * len(rows) + 1.4) + ys = [] + labels = [] + for i, r in enumerate(rows): + for j, (tool, name) in enumerate((("harmonizepy", SUBJECT), ("harmonizr", OTHER))): + y = (len(rows) - 1 - i) * 2.6 + (1 - j) * 1.0 + ys.append(y) + labels.append(f"{r['dataset']} {name}" if j == 0 else name) + left = 0.0 + for key, _name, color, hatch in classes: + share = 100 * r[tool][key] / r["n_features"] + if share <= 0: + continue + ax.barh( + y, + share, + left=left, + height=0.78, + color=color, + edgecolor=t["other"] if hatch else t["bg"], + hatch=hatch, + linewidth=0.8 if hatch else 1.5, + zorder=2, + ) + left += share + missing = r[tool]["empty"] + r[tool]["dropped"] + ax.text( + 101, + y, + f"{r[tool]['corrected'] + r[tool]['raw']:,} of {r['n_features']:,} returned with values" + + (f", {missing:,} without" if missing else ""), + va="center", + fontsize=7.6, + color=t["ink2"], + ) + ax.set_yticks(ys) + ax.set_yticklabels(labels, fontsize=8.6, color=t["ink"]) + ax.tick_params(axis="y", length=0) + ax.set_xlim(0, 100) + ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:g}%")) + ax.grid(False, axis="y") + self.panel( + ax, theme, "Input features by what the output holds for them", "share of input features" + ) + handles = [ + Patch(facecolor=c, edgecolor=t["other"] if h else c, hatch=h, label=n) + for _, n, c, h in classes + ] + self.finish( + fig, + "06-outcomes", + theme, + "Every input feature is in the output", + "ComBat mode 1 on each matrix with an R baseline. Both tools correct the same features; " + f"{SUBJECT} keeps a row for every feature it cannot correct, with its measured values or " + f"empty, and its report says why, where {OTHER} leaves such features out.", + handles, + ncol=4, + ) + + def all(self) -> list[str]: + """Draw every figure its inputs allow, in both themes, and return the stems written.""" + drawn = [("01-speed", self.headline)] + if self.memory_peak: + drawn.append(("02-memory", self.memory_headline)) + if self.scaling: + drawn += [ + ("03-scaling", self.scaling_figure), + ("04-memory-scaling", self.memory), + ("05-blocking", self.blocking), + ] + if self.outcomes: + drawn.append(("06-outcomes", self.outcomes_figure)) + made = [] + for stem, draw in drawn: + for theme in THEMES: + draw(theme) + made.append(f"{stem}-{theme}") + return made + + +def mix(color: str, bg: str, weight: float) -> tuple[float, ...]: + """`weight` of `color` over `bg`, as an opaque color.""" + return tuple( + weight * a + (1 - weight) * b for a, b in zip(to_rgb(color), to_rgb(bg), strict=True) + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="benchmarks.figures", description=__doc__.splitlines()[0]) + parser.add_argument( + "--parity", + default=f"{RESULTS}/benchmark_r_parity.json", + help="JSON of the R-backed parity pass.", + ) + parser.add_argument( + "--memory-peak", + default=f"{RESULTS}/memory_peak.json", + help="JSON of benchmarks.memory_peak.", + ) + parser.add_argument( + "--scaling", default=f"{RESULTS}/scaling.json", help="JSON of benchmarks.scaling." + ) + parser.add_argument( + "--outcomes", default=f"{RESULTS}/outcomes.json", help="JSON of benchmarks.outcomes." + ) + parser.add_argument("--out", default="benchmarks/figures", help="Output directory.") + parser.add_argument( + "--wiki", default="wiki/assets", help="Directory for the wiki's copies; empty to skip them." + ) + args = parser.parse_args(argv) + + def load(path: str) -> dict[str, Any] | None: + """Read a result file; a missing optional one skips its figures.""" + if Path(path).is_file(): + return json.loads(Path(path).read_text()) + print(f"skipped: {path} not found") + return None + + parity = load(args.parity) + if parity is None: + parser.error(f"the parity pass is needed for every figure: {args.parity}") + wiki = Path(args.wiki) if args.wiki else None + made = Figures( + parity, + load(args.scaling), + load(args.outcomes), + Path(args.out), + load(args.memory_peak), + wiki=wiki, + ).all() + print("\n".join(f"wrote {args.out}/{m}.png" for m in made)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmarks/figures/01-speed-dark.png b/benchmarks/figures/01-speed-dark.png new file mode 100644 index 0000000..adb8f32 Binary files /dev/null and b/benchmarks/figures/01-speed-dark.png differ diff --git a/benchmarks/figures/01-speed-light.png b/benchmarks/figures/01-speed-light.png new file mode 100644 index 0000000..3a8cf17 Binary files /dev/null and b/benchmarks/figures/01-speed-light.png differ diff --git a/benchmarks/figures/02-memory-dark.png b/benchmarks/figures/02-memory-dark.png new file mode 100644 index 0000000..050ff06 Binary files /dev/null and b/benchmarks/figures/02-memory-dark.png differ diff --git a/benchmarks/figures/02-memory-light.png b/benchmarks/figures/02-memory-light.png new file mode 100644 index 0000000..21b94bb Binary files /dev/null and b/benchmarks/figures/02-memory-light.png differ diff --git a/benchmarks/figures/03-scaling-dark.png b/benchmarks/figures/03-scaling-dark.png new file mode 100644 index 0000000..6627b57 Binary files /dev/null and b/benchmarks/figures/03-scaling-dark.png differ diff --git a/benchmarks/figures/03-scaling-light.png b/benchmarks/figures/03-scaling-light.png new file mode 100644 index 0000000..5321663 Binary files /dev/null and b/benchmarks/figures/03-scaling-light.png differ diff --git a/benchmarks/figures/04-memory-scaling-dark.png b/benchmarks/figures/04-memory-scaling-dark.png new file mode 100644 index 0000000..682b724 Binary files /dev/null and b/benchmarks/figures/04-memory-scaling-dark.png differ diff --git a/benchmarks/figures/04-memory-scaling-light.png b/benchmarks/figures/04-memory-scaling-light.png new file mode 100644 index 0000000..c666fa3 Binary files /dev/null and b/benchmarks/figures/04-memory-scaling-light.png differ diff --git a/benchmarks/figures/05-blocking-dark.png b/benchmarks/figures/05-blocking-dark.png new file mode 100644 index 0000000..9032f0c Binary files /dev/null and b/benchmarks/figures/05-blocking-dark.png differ diff --git a/benchmarks/figures/05-blocking-light.png b/benchmarks/figures/05-blocking-light.png new file mode 100644 index 0000000..0edcbdd Binary files /dev/null and b/benchmarks/figures/05-blocking-light.png differ diff --git a/benchmarks/figures/06-outcomes-dark.png b/benchmarks/figures/06-outcomes-dark.png new file mode 100644 index 0000000..60d2197 Binary files /dev/null and b/benchmarks/figures/06-outcomes-dark.png differ diff --git a/benchmarks/figures/06-outcomes-light.png b/benchmarks/figures/06-outcomes-light.png new file mode 100644 index 0000000..a37f8ad Binary files /dev/null and b/benchmarks/figures/06-outcomes-light.png differ diff --git a/benchmarks/memory_peak.py b/benchmarks/memory_peak.py new file mode 100644 index 0000000..baea974 --- /dev/null +++ b/benchmarks/memory_peak.py @@ -0,0 +1,157 @@ +"""Peak memory of HarmonizePy and HarmonizR, each in a fresh process, on the same files. + + OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 uv run python -m benchmarks.memory_peak + +Every run starts a new process that reads the data matrix and the batch +description from disk, corrects it once, and exits; the measurement is that +process's peak resident set size (``ru_maxrss`` from ``os.wait4``), the memory +the operating system had to give it. Both tools read the same files, so both +peaks include parsing them. A baseline run per tool loads the interpreter and +the package and stops, which gives the fixed cost of starting the tool. + +HarmonizR runs through ``Rscript`` in the project's renv library, on one +core, with BiocParallel set to serial so that sva's per-batch work stays in the +measured process. Results go to ``benchmarks/results/memory_peak.json``; a run +keeps the measurements already there and adds the missing ones. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +from .datasets import resolve_dataset_paths +from .runners.r_runner import _ensure_tsv +from .scenarios import load_config + +DATASETS = ("small", "murine", "medium", "dia", "scp_small") +ENGINES: tuple[tuple[str, int | None], ...] = (("limma", None), ("ComBat", 1), ("ComBat", 3)) + +_PY = """ +import sys +from harmonizepy import harmonize +if sys.argv[1] != "baseline": + harmonize(sys.argv[2], sys.argv[3], algorithm=sys.argv[1], combat_mode=int(sys.argv[4])) +""" + +_R = """ +args <- commandArgs(trailingOnly = TRUE) +suppressPackageStartupMessages({library(HarmonizR); library(BiocParallel)}) +# sva::ComBat would otherwise take BiocParallel's default multicore workers, whose memory +# the parent process does not report; serial keeps the whole run in one process. +register(SerialParam()) +if (args[1] != "baseline") { + invisible(harmonizR(args[2], args[3], algorithm = args[1], ComBat_mode = as.integer(args[4]), + ur = TRUE, plot = FALSE, output_file = FALSE, verbosity = 0, cores = 1)) +} +""" + + +def peak_rss_mb(cmd: list[str], timeout_s: float) -> tuple[float, float]: + """Run *cmd* to completion and return its peak RSS in MB and its wall time in seconds. + + The child's stderr goes to a temporary file, not a pipe: R and sva write + progress there, and an unread pipe would fill and block the child. + """ + with tempfile.TemporaryFile() as err: + start = time.perf_counter() + proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=err) + deadline = start + timeout_s + while True: + pid, status, usage = os.wait4(proc.pid, os.WNOHANG) + if pid: + break + if time.perf_counter() > deadline: + proc.kill() + os.wait4(proc.pid, 0) + raise TimeoutError(" ".join(cmd[:2])) + time.sleep(0.05) + wall = time.perf_counter() - start + if os.waitstatus_to_exitcode(status) != 0: + err.seek(0) + raise RuntimeError(f"{cmd[0]} failed: {err.read().decode()[-400:]}") + # ru_maxrss is in kilobytes on Linux. + return usage.ru_maxrss / 1024, wall + + +def run(config_path: str, timeout_s: float, out: Path) -> dict[str, Any]: + """Measure every dataset and engine, saving after each one; measurements already in *out* are kept.""" + cfg = load_config(config_path) + tools = { + "harmonizepy": lambda alg, mode, data, desc: [ + sys.executable, + "-c", + _PY, + alg, + data, + desc, + str(mode), + ], + "harmonizr": lambda alg, mode, data, desc: [ + "Rscript", + "-e", + _R, + alg, + data, + desc, + str(mode), + ], + } + report: dict[str, Any] = json.loads(out.read_text()) if out.is_file() else {} + if "baseline_mb" not in report: + report["baseline_mb"] = { + name: peak_rss_mb(make("baseline", 1, "", ""), timeout_s)[0] + for name, make in tools.items() + } + rows: list[dict[str, Any]] = report.setdefault("results", []) + done = {(r["dataset"], r["algorithm"], r["mode"]) for r in rows} + for ds in DATASETS: + paths = resolve_dataset_paths(cfg, ds) + # HarmonizR reads tab-separated text only; both tools get the same file. + data = _ensure_tsv(paths.input_path, cfg.paths_tmp_dir, ds) + for algorithm, mode in ENGINES: + if (ds, algorithm, mode) in done: + continue + row: dict[str, Any] = {"dataset": ds, "algorithm": algorithm, "mode": mode} + for name, make in tools.items(): + peak, wall = peak_rss_mb( + make(algorithm, mode or 1, data, str(paths.desc_path)), timeout_s + ) + row[name] = {"peak_mb": peak, "wall_s": wall} + rows.append(row) + report["generated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + out.write_text(json.dumps(report, indent=2)) + print( + f"{ds} {algorithm} {mode or ''}: py {row['harmonizepy']['peak_mb']:.0f} MB, " + f"R {row['harmonizr']['peak_mb']:.0f} MB", + flush=True, + ) + return report + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="benchmarks.memory_peak", description=__doc__.splitlines()[0] + ) + parser.add_argument("--config", default="benchmarks/config.yaml", help="Benchmark config.") + parser.add_argument("--timeout", type=float, default=1800, help="Seconds allowed per run.") + parser.add_argument( + "--out", default="benchmarks/results/memory_peak.json", help="Output JSON path." + ) + args = parser.parse_args(argv) + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + run(args.config, args.timeout, out) + print(f"Results written to {out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmarks/outcomes.py b/benchmarks/outcomes.py new file mode 100644 index 0000000..1a4c759 --- /dev/null +++ b/benchmarks/outcomes.py @@ -0,0 +1,117 @@ +"""What each tool returns for every input feature, on the datasets with an R baseline. + + uv run python -m benchmarks.outcomes + +reads the parity pass at ``benchmarks/results/benchmark_r_parity.json`` and +writes ``benchmarks/results/outcomes.json``. + +For ComBat mode 1, the default, each input feature is put in one class per tool: + +- ``corrected``: returned with values that differ from the input; +- ``raw``: returned with its input values unchanged (HarmonizePy reports why); +- ``empty``: returned as a row with no value; +- ``dropped``: not in the output at all. + +HarmonizePy's classes come from its correction report. HarmonizR's come from +the cached output of the parity pass: a returned row is ``raw`` when every value +it has equals the input's in the same cells. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +from harmonizepy import harmonize + +from .datasets import load_dataset, resolve_dataset_paths +from .scenarios import load_config + +CLASSES = ("corrected", "raw", "empty", "dropped") + + +def _harmonizr_classes(data: pd.DataFrame, r_out: pd.DataFrame) -> dict[str, int]: + shared = data.index.intersection(r_out.index) + cols = data.columns.intersection(r_out.columns) + given = data.loc[shared, cols].to_numpy(dtype=np.float64) + got = r_out.loc[shared, cols].to_numpy(dtype=np.float64) + empty = np.isnan(got).all(axis=1) + both = ~np.isnan(got) & ~np.isnan(given) + diff = np.where(both, np.abs(got - given), 0.0) + tolerance = 1e-9 * np.maximum(np.abs(np.nan_to_num(given)), 1.0) + unchanged = (diff <= tolerance).all(axis=1) + raw = ~empty & unchanged + return { + "corrected": int((~empty & ~unchanged).sum()), + "raw": int(raw.sum()), + "empty": int(empty.sum()), + "dropped": len(data.index.difference(r_out.index)), + } + + +def run(parity_path: str, config_path: str) -> dict[str, Any]: + parity = json.loads(Path(parity_path).read_text()) + cfg = load_config(config_path) + rows = [] + for e in parity["results"]: + s = e["scenario"] + if ( + s["algorithm"] != "ComBat" + or s.get("combat_mode") != 1 + or s.get("block") + or not e.get("r") + ): + continue + data, desc = load_dataset(resolve_dataset_paths(cfg, s["dataset"])) + _, report = harmonize(data, desc, return_report=True) + status = report["status"] + py = { + "corrected": int((status == "corrected").sum()), + "raw": int(status.str.startswith("raw_").sum()), + "empty": int((status == "missing_no_usable_batch").sum()), + "dropped": 0, + } + raw_reasons = { + k: int(v) for k, v in status[status.str.startswith("raw_")].value_counts().items() + } + r_out = pd.read_csv(e["r"]["output_tsv"], sep="\t", index_col=0) + rows.append( + { + "dataset": s["dataset"], + "n_features": len(data), + "harmonizepy": py, + "harmonizepy_raw_reasons": raw_reasons, + "harmonizr": _harmonizr_classes(data, r_out), + } + ) + print(f"{s['dataset']}: done", flush=True) + return {"combat_mode": 1, "classes": list(CLASSES), "datasets": rows} + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + prog="benchmarks.outcomes", description=__doc__.splitlines()[0] + ) + parser.add_argument( + "--parity", + default="benchmarks/results/benchmark_r_parity.json", + help="JSON of the R-backed parity pass.", + ) + parser.add_argument("--config", default="benchmarks/config.yaml", help="Benchmark config.") + parser.add_argument( + "--out", default="benchmarks/results/outcomes.json", help="Output JSON path." + ) + args = parser.parse_args(argv) + report = run(args.parity, args.config) + Path(args.out).write_text(json.dumps(report, indent=2)) + print(f"Results written to {args.out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/benchmarks/report.py b/benchmarks/report.py index 471b814..d770b79 100644 --- a/benchmarks/report.py +++ b/benchmarks/report.py @@ -1,8 +1,8 @@ """JSON and Markdown report generation for benchmark results. Converts harness ``ScenarioResult`` tuples into the v2.0 output JSON -schema (plan Section 13) and generates human-readable Markdown reports -comparable to the old ``benchmarks/RESULTS.md``. +schema and generates human-readable Markdown reports in the layout of +``benchmarks/RESULTS.md``. Usage:: @@ -21,7 +21,6 @@ import platform import statistics from datetime import UTC, datetime -from importlib.metadata import version from pathlib import Path from typing import Any, cast @@ -68,11 +67,14 @@ def build_report_json( r_cores = r_cores or config.r_cache_default_cores # System info + import harmonizepy + system = { "os": f"{platform.system()} {platform.release()}", - "cpu": platform.processor() or "unknown", + "cpu": _cpu_model(), + "blas_threads": _blas_threads_setting(), "python": platform.python_version(), - "harmonizepy": version("harmonizepy"), + "harmonizepy": harmonizepy.__version__, "r": r_version, "r_available": r_version is not None, "harmonizr": harmonizr_version, @@ -104,12 +106,15 @@ def build_report_json( baseline = "Python + R" if ds_spec.r_eligible else "Python only" # Calculate file sizes from .datasets import resolve_dataset_paths + try: paths = resolve_dataset_paths(config, ds_name) input_size = paths.input_path.stat().st_size if paths.input_path.is_file() else 0 desc_size = paths.desc_path.stat().st_size if paths.desc_path.is_file() else 0 total_kb = (input_size + desc_size) / 1024.0 - size_str = f"{total_kb:.0f} KB" if total_kb < 1024 else f"{total_kb / 1024.0:.1f} MB" + size_str = ( + f"{total_kb:.0f} KB" if total_kb < 1024 else f"{total_kb / 1024.0:.1f} MB" + ) except OSError: size_str = "N/A" datasets_meta[ds_name] = { @@ -123,8 +128,13 @@ def build_report_json( } except KeyError: datasets_meta[ds_name] = { - "type": "Unknown", "baseline": "Unknown", "features": 0, "samples": 0, "batches": 0, - "file_size": "N/A", "missing_frac": None, + "type": "Unknown", + "baseline": "Unknown", + "features": 0, + "samples": 0, + "batches": 0, + "file_size": "N/A", + "missing_frac": None, } return { @@ -165,13 +175,25 @@ def _build_scenario_entry( "p5_s": s_metrics.p5_s, "p95_s": s_metrics.p95_s, "cpu_pct": statistics.median(s_metrics.cpu_pcts) if s_metrics.cpu_pcts else None, - "tracemalloc_peak_mb": statistics.median(s_metrics.tracemalloc_peak_mbs) if s_metrics.tracemalloc_peak_mbs else None, + "tracemalloc_peak_mb": statistics.median(s_metrics.tracemalloc_peak_mbs) + if s_metrics.tracemalloc_peak_mbs + else None, "rss_post_gc_kbs": s_metrics.rss_post_gc_kbs, - "rss_before_kb": statistics.median(s_metrics.rss_before_kbs) if s_metrics.rss_before_kbs else None, - "rss_after_kb": statistics.median(s_metrics.rss_after_kbs) if s_metrics.rss_after_kbs else None, - "rss_post_gc_kb": statistics.median(s_metrics.rss_post_gc_kbs) if s_metrics.rss_post_gc_kbs else None, - "rss_delta_kb": statistics.median(s_metrics.rss_delta_kbs) if s_metrics.rss_delta_kbs else None, - "rss_delta_post_gc_kb": statistics.median(s_metrics.rss_delta_post_gc_kbs) if s_metrics.rss_delta_post_gc_kbs else None, + "rss_before_kb": statistics.median(s_metrics.rss_before_kbs) + if s_metrics.rss_before_kbs + else None, + "rss_after_kb": statistics.median(s_metrics.rss_after_kbs) + if s_metrics.rss_after_kbs + else None, + "rss_post_gc_kb": statistics.median(s_metrics.rss_post_gc_kbs) + if s_metrics.rss_post_gc_kbs + else None, + "rss_delta_kb": statistics.median(s_metrics.rss_delta_kbs) + if s_metrics.rss_delta_kbs + else None, + "rss_delta_post_gc_kb": statistics.median(s_metrics.rss_delta_post_gc_kbs) + if s_metrics.rss_delta_post_gc_kbs + else None, "rss_stability": { "status": s_metrics.rss_stability.status, "reason": s_metrics.rss_stability.reason, @@ -207,10 +229,9 @@ def _build_scenario_entry( } comp_type = "realistic" if r_cores and r_cores > 1 else "single_core_fair" note = ( - f"R={r_cores} cores (foreach/doParallel), " - f"Python=1 thread (NumPy single-threaded)." - ) if r_cores and r_cores > 1 else ( - "R=1 core, Python=1 thread. Equal threading, startup excluded." + (f"R={r_cores} cores (foreach/doParallel), Python=1 thread (NumPy single-threaded).") + if r_cores and r_cores > 1 + else ("R=1 core, Python=1 thread. Equal threading, startup excluded.") ) comparison_meta = { "r_cores": r_cores, @@ -231,6 +252,8 @@ def _build_scenario_entry( "concordance_mean_rel": validity.concordance_mean_rel, "concordance_nan_match": validity.concordance_nan_match, "concordance_shared_features": validity.concordance_shared_features, + "concordance_py_only_features": validity.concordance_py_only_features, + "concordance_r_only_features": validity.concordance_r_only_features, "error": validity.error, } @@ -265,10 +288,31 @@ def read_report_json(path: str | Path) -> dict[str, Any]: # --------------------------------------------------------------------------- -def _detect_blas_threads() -> int: - """Detect available BLAS threads from the system.""" +def _cpu_model() -> str: + """Return the CPU model name: ``/proc/cpuinfo`` on Linux, else what ``platform`` reports.""" + try: + with Path("/proc/cpuinfo").open(encoding="utf-8") as cpuinfo: + for line in cpuinfo: + if line.startswith("model name"): + return line.split(":", 1)[1].strip() + except OSError: + pass + return platform.processor() or platform.machine() or "unknown" + + +def _blas_threads_setting() -> str: + """Return the BLAS thread limit the environment sets for this run. + + ``OPENBLAS_NUM_THREADS``, ``OMP_NUM_THREADS``, and ``MKL_NUM_THREADS`` are + checked in that order; without them, OpenBLAS starts one thread per core. + """ import os - return os.cpu_count() or 32 + + for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): + value = os.environ.get(name) + if value: + return value + return f"not limited ({os.cpu_count()} cores)" def generate_markdown(report: dict[str, Any]) -> str: @@ -276,7 +320,7 @@ def generate_markdown(report: dict[str, Any]) -> str: system = report.get("system", {}) results = report.get("results", []) - blas_threads = _detect_blas_threads() + blas_threads = system.get("blas_threads", "not recorded") r_cores_str = "N/A" for entry in results: @@ -295,8 +339,12 @@ def generate_markdown(report: dict[str, Any]) -> str: lines.append(f"**Generated:** {report.get('generated_at', '')}") lines.append(f"**Platform:** {system.get('os', '')}") lines.append(f"**CPU:** {system.get('cpu', '')}") - lines.append(f"**Threads:** Python=1 thread, R={r_cores_str} core(s), System/BLAS={blas_threads} threads") - lines.append(f"**Python:** {system.get('python', '')} (harmonizepy v{system.get('harmonizepy', '')})") + lines.append( + f"**Threads:** Python=1 thread, R={r_cores_str} core(s), BLAS threads={blas_threads}" + ) + lines.append( + f"**Python:** {system.get('python', '')} (harmonizepy v{system.get('harmonizepy', '')})" + ) if system.get("r"): lines.append(f"**R:** {system['r']} (HarmonizR {system.get('harmonizr', 'N/A')})") lines.append("") @@ -337,7 +385,9 @@ def _add_data_specs(lines: list[str], report: dict[str, Any]) -> None: lines.append("## Data Specifications") lines.append("") - lines.append("| Dataset | Type | Baseline | Features | Samples | Batches | Missing | File Size |") + lines.append( + "| Dataset | Type | Baseline | Features | Samples | Batches | Missing | File Size |" + ) lines.append("| --- | --- | --- | --- | --- | --- | --- | --- |") for ds_name in sorted(datasets_meta): meta = datasets_meta[ds_name] @@ -361,10 +411,7 @@ def _add_data_specs(lines: list[str], report: dict[str, Any]) -> None: def _has_r_data(results: list[dict[str, Any]]) -> bool: - return any( - r.get("r") and r["r"].get("median_s") is not None - for r in results - ) + return any(r.get("r") and r["r"].get("median_s") is not None for r in results) def _add_speed_section(lines: list[str], results: list[dict[str, Any]], r_cores: str) -> None: @@ -375,19 +422,23 @@ def _add_speed_section(lines: list[str], results: list[dict[str, Any]], r_cores: lines.append("## Speed") lines.append("") - lines.append(f"Wall-clock time per scenario. Python runs single-threaded. R uses {r_cores} core(s) with system BLAS threading.") + lines.append( + f"Wall-clock time per scenario. Python starts no threads of its own; BLAS uses the thread limit in the header. R uses {r_cores} core(s)." + ) has_r = _has_r_data(results) if has_r: - lines.append("Rows with `--` in the R columns are intentional Python-only scenarios or scenarios without a cached R baseline.") + lines.append( + "Rows with `--` in the R columns are intentional Python-only scenarios or scenarios without a cached R baseline." + ) lines.append("") header = "| Dataset | Algorithm | Mode | Block | Sort | Py Med (s) | Py Reps" - sep = "| --- | --- | --- | --- | --- | --- | ---" + sep = "| --- | --- | --- | --- | --- | --- | ---" if has_r: header += " | R Med (s) | R Reps | Ratio (R/Py)" - sep += " | --- | --- | ---" + sep += " | --- | --- | ---" header += " |" - sep += " |" + sep += " |" lines.append(header) lines.append(sep) @@ -433,17 +484,21 @@ def _add_memory_section(lines: list[str], results: list[dict[str, Any]], r_cores lines.append("## Memory") lines.append("") - lines.append("Python RSS retained delta is measured from a post-GC baseline before the call to a post-GC RSS after transient benchmark objects are released. This is more stable across repeated in-process runs than a raw before/after delta. RSS stability summarizes the repeated timed runs: plateau means the last up to 3 post-GC samples stayed within 1024 KB, and growing means monotonic growth without a stable tail. Raw end-of-call RSS is still stored in the JSON output. Heap is Python tracemalloc peak and R gc() absolute heap. R runs all scenarios in one process, so later scenarios may reuse previously allocated memory.") + lines.append( + "Python RSS retained delta is measured from a post-GC baseline before the call to a post-GC RSS after transient benchmark objects are released. This is more stable across repeated in-process runs than a raw before/after delta. RSS stability summarizes the repeated timed runs: plateau means the last up to 3 post-GC samples stayed within 1024 KB, and growing means monotonic growth without a stable tail. Raw end-of-call RSS is still stored in the JSON output. Heap is Python tracemalloc peak and R gc() absolute heap. R runs all scenarios in one process, so later scenarios may reuse previously allocated memory." + ) has_r = _has_r_data(results) if has_r: - lines.append("Rows with blank R memory fields are intentional Python-only scenarios or scenarios without a cached R baseline.") + lines.append( + "Rows with blank R memory fields are intentional Python-only scenarios or scenarios without a cached R baseline." + ) lines.append("") header = "| Dataset | Algorithm | Mode | Py RSS stability | Py RSS retained Δ (KB) | R RSS Δ (KB) | Py RSS post-GC (KB) | Py Heap (MB) | R Heap (MB) |" - sep = "| --- | --- | --- | --- | --- | --- | --- | --- | --- |" + sep = "| --- | --- | --- | --- | --- | --- | --- | --- | --- |" if not has_r: header = "| Dataset | Algorithm | Mode | Py RSS stability | Py RSS retained Δ (KB) | Py RSS post-GC (KB) | Py Heap (MB) |" - sep = "| --- | --- | --- | --- | --- | --- | --- |" + sep = "| --- | --- | --- | --- | --- | --- | --- |" lines.append(header) lines.append(sep) @@ -461,15 +516,23 @@ def _add_memory_section(lines: list[str], results: list[dict[str, Any]], r_cores if py.get("rss_delta_post_gc_kb") is not None else "--" ) - py_rss_post_gc = f"{py.get('rss_post_gc_kb', 0):.0f}" if py.get("rss_post_gc_kb") is not None else "--" - py_heap = f"{py.get('tracemalloc_peak_mb', 0):.2f}" if py.get("tracemalloc_peak_mb") is not None else "--" + py_rss_post_gc = ( + f"{py.get('rss_post_gc_kb', 0):.0f}" if py.get("rss_post_gc_kb") is not None else "--" + ) + py_heap = ( + f"{py.get('tracemalloc_peak_mb', 0):.2f}" + if py.get("tracemalloc_peak_mb") is not None + else "--" + ) row = f"| {ds} | {algo} | {mode} | {py_rss_stability_status} | {py_rss} |" if has_r: r_data = r.get("r") if r_data and r_data.get("rss_delta_kb") is not None: r_rss = f"{r_data['rss_delta_kb']:.0f}" - r_heap = f"{r_data['r_heap_mb']:.1f}" if r_data.get("r_heap_mb") is not None else "--" + r_heap = ( + f"{r_data['r_heap_mb']:.1f}" if r_data.get("r_heap_mb") is not None else "--" + ) else: r_rss = "--" r_heap = "--" @@ -500,13 +563,17 @@ def _add_concordance_section(lines: list[str], results: list[dict[str, Any]]) -> lines.append("## Concordance") lines.append("") - lines.append("Python vs R corrected output comparison on shared features. Relative difference is |py - r| / |r| for non-NaN cells. Only scenarios with an R baseline appear below.") + lines.append( + "Python vs R corrected output comparison on shared features. Relative difference is |py - r| / |r| for non-NaN cells. Only scenarios with an R baseline appear below." + ) lines.append("") - lines.extend([ - "| Dataset | Algorithm | Mode | Block | Sort | Shared Features | Py Only | R Only | NaN Match | Max Rel | Mean Rel |", - "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |", - ]) + lines.extend( + [ + "| Dataset | Algorithm | Mode | Block | Sort | Shared Features | Py Only | R Only | NaN Match | Max Rel | Mean Rel |", + "| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |", + ] + ) for r in conc_rows: sc = r["scenario"] v = r["validity"] @@ -520,7 +587,11 @@ def _add_concordance_section(lines: list[str], results: list[dict[str, Any]]) -> r_only = str(v.get("concordance_r_only_features", "")) nm = "YES" if v.get("concordance_nan_match") else "NO" mr = f"{v['concordance_max_rel']:.2e}" if v.get("concordance_max_rel") is not None else "--" - mn = f"{v['concordance_mean_rel']:.2e}" if v.get("concordance_mean_rel") is not None else "--" + mn = ( + f"{v['concordance_mean_rel']:.2e}" + if v.get("concordance_mean_rel") is not None + else "--" + ) lines.append( f"| {ds} | {algo} | {mode} | {block} | {sort} | " f"{shared} | {py_only} | {r_only} | {nm} | {mr} | {mn} |" diff --git a/benchmarks/scaling.py b/benchmarks/scaling.py new file mode 100644 index 0000000..0a9901f --- /dev/null +++ b/benchmarks/scaling.py @@ -0,0 +1,179 @@ +"""Scaling sweep: wall time and peak memory of ``harmonize()`` against matrix size. + + OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 uv run python -m benchmarks.scaling + +Synthetic matrices from ``generate_dataset`` (per-batch missingness, 20 percent +of features absent from each batch, ten batches) are corrected with limma and +the four ComBat modes: + +- a feature sweep at 60 samples; +- a sample sweep at 5000 features; +- a blocking pair, without and with ``block=2``, which also records the share + of observed input values that reach the output. + +Each point is timed with the harness's ``run_once``, so wall time and peak +memory are measured as in the main benchmark; the reported time is the median +of the repetitions. Only Python runs here: R baselines come from the parity +pass of ``benchmarks.bench``. Results go to ``benchmarks/results/scaling.json``. +""" + +from __future__ import annotations + +import argparse +import json +import os +import platform +import statistics +import time +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd + +import harmonizepy +from harmonizepy.core import plan_affiliations, prepare_inputs + +from .datasets import generate_dataset +from .runners.python_runner import run_once +from .scenarios import Scenario + +FEATURES = (1_000, 2_000, 5_000, 10_000, 20_000, 50_000) +SAMPLES = (40, 100, 200, 600, 2_000, 6_000) +QUICK_FEATURES = (1_000, 2_000) +QUICK_SAMPLES = (40, 100) +ENGINES: tuple[tuple[str, int | None], ...] = ( + ("limma", None), + ("ComBat", 1), + ("ComBat", 2), + ("ComBat", 3), + ("ComBat", 4), +) +N_BATCHES = 10 +MISSING_FRAC = 0.20 +# Points slower than this get one repetition instead of three. +SLOW_S = 20.0 + + +def _measure( + data: pd.DataFrame, desc: pd.DataFrame, algorithm: str, mode: int | None, block: int | None +) -> dict[str, Any]: + """Time one configuration and return its record, keeping the output for one count.""" + scenario = Scenario(dataset="sweep", algorithm=algorithm, combat_mode=mode, block=block) + first = run_once(data, desc, scenario, keep_result_df=True) + result = first.result["result_df"] + observed_out = int(result.notna().to_numpy().sum()) + first.release_result() + runs = [first] + if first.elapsed_s < SLOW_S: + runs += [run_once(data, desc, scenario, keep_result_df=False) for _ in range(2)] + return { + **_groups(data, desc, algorithm, mode, block), + "algorithm": algorithm, + "mode": mode, + "block": block, + "n_features": data.shape[0], + "n_samples": data.shape[1], + "n_batches": N_BATCHES, + "reps": len(runs), + "median_s": statistics.median(r.elapsed_s for r in runs), + "peak_mb": max(r.tracemalloc_peak_mb for r in runs), + "input_mb": data.to_numpy().nbytes / 2**20, + "observed_in": int(data.notna().to_numpy().sum()), + "observed_out": observed_out, + } + + +def _groups( + data: pd.DataFrame, desc: pd.DataFrame, algorithm: str, mode: int | None, block: int | None +) -> dict[str, int]: + """Count the affiliation groups a run forms, and those big enough for an engine.""" + inputs = prepare_inputs( + data, + desc, + algorithm=algorithm, + combat_mode=mode or 1, + needed_values=None, + sort=None, + block=block, + unique_removal=True, + ) + plan = plan_affiliations( + inputs.data, + inputs.batch_list, + sort=None, + block=block, + needed_values=inputs.needed_values, + unique_removal=True, + ) + sizes = pd.Series([a for a in plan.affiliation_list if a]).value_counts() + return {"n_groups": int(sizes.size), "n_groups_fitted": int((sizes >= 2).sum())} + + +def _matrix(n_features: int, n_samples: int) -> tuple[pd.DataFrame, pd.DataFrame]: + return generate_dataset( + "sweep", n_features, n_samples, N_BATCHES, MISSING_FRAC, missing_mode="per_batch" + ) + + +def run_sweep(*, quick: bool = False) -> dict[str, Any]: + """Run the three sweeps and return them with the environment they ran in.""" + records: dict[str, list[dict[str, Any]]] = {"features": [], "samples": [], "blocking": []} + for n_features in QUICK_FEATURES if quick else FEATURES: + data, desc = _matrix(n_features, 60) + for algorithm, mode in ENGINES: + records["features"].append(_measure(data, desc, algorithm, mode, None)) + print(f"features {n_features}: {algorithm} {mode or ''} done", flush=True) + for n_samples in QUICK_SAMPLES if quick else SAMPLES: + data, desc = _matrix(5_000, n_samples) + for algorithm, mode in ENGINES: + records["samples"].append(_measure(data, desc, algorithm, mode, None)) + print(f"samples {n_samples}: {algorithm} {mode or ''} done", flush=True) + for n_features in QUICK_FEATURES[:1] if quick else (5_000, 20_000): + data, desc = _matrix(n_features, 60) + for algorithm, mode in (("limma", None), ("ComBat", 1), ("ComBat", 3)): + for block in (None, 2): + records["blocking"].append(_measure(data, desc, algorithm, mode, block)) + print(f"blocking {n_features} done", flush=True) + return { + "generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "system": { + "os": f"{platform.system()} {platform.release()}", + "python": platform.python_version(), + "numpy": np.__version__, + "pandas": pd.__version__, + "harmonizepy": harmonizepy.__version__, + "blas_threads": os.environ.get("OPENBLAS_NUM_THREADS") + or os.environ.get("OMP_NUM_THREADS") + or "unset", + }, + "design": { + "n_batches": N_BATCHES, + "missing_frac": MISSING_FRAC, + "missing_mode": "per_batch", + "feature_sweep_samples": 60, + "sample_sweep_features": 5_000, + }, + **records, + } + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="benchmarks.scaling", description=__doc__.splitlines()[0]) + parser.add_argument( + "--out", default="benchmarks/results/scaling.json", help="Output JSON path." + ) + parser.add_argument( + "--quick", action="store_true", help="Two small sizes per sweep, for a smoke run." + ) + args = parser.parse_args(argv) + report = run_sweep(quick=args.quick) + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text(json.dumps(report, indent=2)) + print(f"Results written to {out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/pyproject.toml b/pyproject.toml index 172330e..eb8520b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "harmonizepy" -version = "0.3.2" +version = "0.4.0" description = "Pure-Python batch-effect harmonization (ComBat + limma), validated against R sva/HarmonizR." readme = "README.md" license = "GPL-3.0-only" @@ -24,13 +24,13 @@ dependencies = [ ] [project.optional-dependencies] -# pip install harmonizepy[config] → enables YAML and TOML config files +# pip install harmonizepy[config] → enables YAML config files (TOML and JSON need no extra) config = [ "pyyaml>=6.0", ] # pip install harmonizepy[completion] → enables shell tab-completion via argcomplete completion = ["argcomplete>=3.0"] -# pip install harmonizepy[io] → pyarrow for faster IO and parquet output +# pip install harmonizepy[io] → pyarrow for Parquet input and output io = [ "pyarrow>=14.0", ] @@ -55,13 +55,19 @@ dev = [ "ty>=0.0.72", "pandas-stubs>=2.0", ] +# uv sync --group figures -> the benchmark figures (python -m benchmarks.figures) +figures = [ + "matplotlib>=3.8", + "pillow>=10.0", +] [build-system] requires = ["hatchling>=1.25"] build-backend = "hatchling.build" [tool.pytest.ini_options] -testpaths = ["tests"] +testpaths = ["tests", "src/harmonizepy"] +addopts = "--doctest-modules" [tool.coverage.run] source = ["src/harmonizepy"] diff --git a/renv.lock b/renv.lock index a11ade2..0fbe37c 100644 --- a/renv.lock +++ b/renv.lock @@ -1,6 +1,6 @@ { "R": { - "Version": "4.6.1", + "Version": "4.6.2", "Repositories": [ { "Name": "CRAN", @@ -700,11 +700,11 @@ }, "MASS": { "Package": "MASS", - "Version": "7.3-65", + "Version": "7.3-66", "Source": "Repository", "Priority": "recommended", - "Date": "2025-02-19", - "Revision": "$Rev: 3681 $", + "Date": "2026-07-15", + "Revision": "$Rev: 3693 $", "Depends": [ "R (>= 4.4.0)", "grDevices", @@ -736,16 +736,16 @@ }, "Matrix": { "Package": "Matrix", - "Version": "1.7-5", + "Version": "1.7-6", "Source": "Repository", "VersionNote": "do also bump src/version.h, inst/include/Matrix/version.h", - "Date": "2026-03-20", + "Date": "2026-07-24", "Priority": "recommended", "Title": "Sparse and Dense Matrix Classes and Methods", "Description": "A rich hierarchy of sparse and dense matrix classes, including general, symmetric, triangular, and diagonal matrices with numeric, logical, or pattern entries. Efficient methods for operating on such matrices, often wrapping the 'BLAS', 'LAPACK', and 'SuiteSparse' libraries.", "License": "GPL (>= 2) | file LICENCE", - "URL": "https://Matrix.R-forge.R-project.org", - "BugReports": "https://R-forge.R-project.org/tracker/?atid=294&group_id=61", + "URL": "https://codeberg.org/jaganmn/Matrix", + "BugReports": "https://codeberg.org/jaganmn/Matrix/issues", "Contact": "Matrix-authors@R-project.org", "Authors@R": "c(person(\"Douglas\", \"Bates\", role = \"aut\", comment = c(ORCID = \"0000-0001-8316-9503\")), person(\"Martin\", \"Maechler\", role = c(\"aut\", \"cre\"), email = \"mmaechler+Matrix@gmail.com\", comment = c(ORCID = \"0000-0002-8685-9910\")), person(\"Mikael\", \"Jagan\", role = \"aut\", comment = c(ORCID = \"0000-0002-3542-2938\")), person(\"Timothy A.\", \"Davis\", role = \"ctb\", comment = c(ORCID = \"0000-0001-7614-6899\", \"SuiteSparse libraries\", \"collaborators listed in dir(system.file(\\\"doc\\\", \\\"SuiteSparse\\\", package=\\\"Matrix\\\"), pattern=\\\"License\\\", full.names=TRUE, recursive=TRUE)\")), person(\"George\", \"Karypis\", role = \"ctb\", comment = c(ORCID = \"0000-0003-2753-1437\", \"METIS library\", \"Copyright: Regents of the University of Minnesota\")), person(\"Jason\", \"Riedy\", role = \"ctb\", comment = c(ORCID = \"0000-0002-4345-4200\", \"GNU Octave's condest() and onenormest()\", \"Copyright: Regents of the University of California\")), person(\"Jens\", \"Oehlschlägel\", role = \"ctb\", comment = \"initial nearPD()\"), person(\"R Core Team\", role = \"ctb\", comment = c(ROR = \"02zz1nj61\", \"base R's matrix implementation\")))", "Depends": [ @@ -1673,10 +1673,10 @@ }, "cluster": { "Package": "cluster", - "Version": "2.1.8.2", + "Version": "2.1.8.3", "Source": "Repository", - "VersionNote": "Last CRAN: 2.1.8.1 on 2025-03-11; 2.1.8 on 2024-12-10; 2.1.7 on 2024-12-06; 2.1.6 on 2023-11-30;", - "Date": "2026-02-03", + "VersionNote": "Last CRAN: 2.1.8.2 on 2026-02-03; 2.1.8.1 on 2025-03-11; 2.1.8 on 2024-12-10; 2.1.7 on 2024-12-06;", + "Date": "2026-07-28", "Priority": "recommended", "Title": "\"Finding Groups in Data\": Cluster Analysis Extended Rousseeuw et al.", "Description": "Methods for Cluster analysis. Much extended the original from Peter Rousseeuw, Anja Struyf and Mia Hubert, based on Kaufman and Rousseeuw (1990) \"Finding Groups in Data\".", @@ -2510,9 +2510,9 @@ }, "lattice": { "Package": "lattice", - "Version": "0.22-9", + "Version": "0.23-1", "Source": "Repository", - "Date": "2026-02-03", + "Date": "2026-08-08", "Priority": "recommended", "Title": "Trellis Graphics for R", "Authors@R": "c(person(\"Deepayan\", \"Sarkar\", role = c(\"aut\", \"cre\"), email = \"deepayan.sarkar@r-project.org\", comment = c(ORCID = \"0000-0003-4107-1553\")), person(\"Felix\", \"Andrews\", role = \"ctb\"), person(\"Kevin\", \"Wright\", role = \"ctb\", comment = \"documentation\"), person(\"Neil\", \"Klepeis\", role = \"ctb\"), person(\"Johan\", \"Larsson\", role = \"ctb\", comment = \"miscellaneous improvements\"), person(\"Zhijian (Jason)\", \"Wen\", role = \"cph\", comment = \"filled contour code\"), person(\"Paul\", \"Murrell\", role = \"ctb\", email = \"paul@stat.auckland.ac.nz\"), person(\"Stefan\", \"Eng\", role = \"ctb\", comment = \"violin plot improvements\"), person(\"Achim\", \"Zeileis\", role = \"ctb\", comment = \"modern colors\"), person(\"Alexandre\", \"Courtiol\", role = \"ctb\", comment = \"generics for larrows, lpolygon, lrect and lsegments\") )", @@ -2856,9 +2856,9 @@ }, "nlme": { "Package": "nlme", - "Version": "3.1-169", + "Version": "3.1-171", "Source": "Repository", - "Date": "2026-03-27", + "Date": "2026-09-01", "Priority": "recommended", "Title": "Linear and Nonlinear Mixed Effects Models", "Authors@R": "c(person(\"José\", \"Pinheiro\", role = \"aut\", comment = \"S version\"), person(\"Douglas\", \"Bates\", role = \"aut\", comment = \"up to 2007\"), person(\"Saikat\", \"DebRoy\", role = \"ctb\", comment = \"up to 2002\"), person(\"Deepayan\", \"Sarkar\", role = \"ctb\", comment = \"up to 2005\"), person(\"EISPACK authors\", role = \"ctb\", comment = \"src/rs.f\"), person(\"Siem\", \"Heisterkamp\", role = \"ctb\", comment = \"Author fixed sigma\"), person(\"Bert\", \"Van Willigen\",role = \"ctb\", comment = \"Programmer fixed sigma\"), person(\"Johannes\", \"Ranke\", role = \"ctb\", comment = \"varConstProp()\"), person(\"R Core Team\", email = \"R-core@R-project.org\", role = c(\"aut\", \"cre\"), comment = c(ROR = \"02zz1nj61\")))", @@ -2874,8 +2874,7 @@ "lattice" ], "Suggests": [ - "MASS", - "SASmixed" + "MASS" ], "LazyData": "yes", "Encoding": "UTF-8", @@ -3500,13 +3499,13 @@ }, "survival": { "Package": "survival", - "Version": "3.8-6", + "Version": "3.8-12", "Source": "Repository", "Title": "Survival Analysis", "Priority": "recommended", - "Date": "2026-01-09", + "Date": "2026-09-02", "Depends": [ - "R (>= 3.5.0)" + "R (>= 4.1.0)" ], "Imports": [ "graphics", @@ -3519,13 +3518,13 @@ "LazyData": "Yes", "LazyDataCompression": "xz", "ByteCompile": "Yes", - "Authors@R": "c(person(c(\"Terry\", \"M\"), \"Therneau\", email=\"therneau.terry@mayo.edu\", role=c(\"aut\", \"cre\")), person(\"Thomas\", \"Lumley\", role=c(\"ctb\", \"trl\"), comment=\"original S->R port and R maintainer until 2009\"), person(\"Atkinson\", \"Elizabeth\", role=\"ctb\"), person(\"Crowson\", \"Cynthia\", role=\"ctb\"))", + "Authors@R": "c(person(c(\"Terry\", \"M\"), \"Therneau\", email=\"terry.therneau@proton.me\", role=c(\"aut\", \"cre\")), person(\"Thomas\", \"Lumley\", role=c(\"ctb\", \"trl\"), comment=\"original S->R port and R maintainer until 2009\"), person(\"Atkinson\", \"Elizabeth\", role=\"ctb\"), person(\"Crowson\", \"Cynthia\", role=\"ctb\"))", "Description": "Contains the core survival analysis routines, including definition of Surv objects, Kaplan-Meier and Aalen-Johansen (multi-state) curves, Cox models, and parametric accelerated failure time models.", "License": "LGPL (>= 2)", "URL": "https://github.com/therneau/survival", "NeedsCompilation": "yes", "Author": "Terry M Therneau [aut, cre], Thomas Lumley [ctb, trl] (original S->R port and R maintainer until 2009), Atkinson Elizabeth [ctb], Crowson Cynthia [ctb]", - "Maintainer": "Terry M Therneau ", + "Maintainer": "Terry M Therneau ", "Repository": "CRAN" }, "sva": { diff --git a/src/harmonizepy/__init__.py b/src/harmonizepy/__init__.py index 1923da4..7766efe 100644 --- a/src/harmonizepy/__init__.py +++ b/src/harmonizepy/__init__.py @@ -1,18 +1,22 @@ -"""HarmonizePy - batch-effect harmonization in pure Python.""" +"""Batch-effect correction for omics matrices with missing values, in pure Python. + +The public names are listed in ``__all__``: the ``harmonize()`` pipeline, the +ComBat and limma engines, their DataFrame wrappers, the run configuration, +and the input-scale warning. Custom pipelines can also use +``harmonizepy.sorting.sort_batches``, ``harmonizepy.blocking.build_block_list``, +and ``harmonizepy.affiliation.remove_unique_combinations``. +""" from __future__ import annotations -# --------------------------------------------------------------------------- -# Public API, importable directly from `harmonizepy` -# --------------------------------------------------------------------------- from .combat import combat from .combat_wrapper import adjust_combat from .core import harmonize from .limma_wrapper import adjust_limma, remove_batch_effect -from .types import HarmonizeConfig +from .types import HarmonizeConfig, HarmonizeResult +from .validation import InputScaleWarning -# __all__ intentionally grouped by semantic tier, not alphabetical. -# ruff: noqa: RUF022 +# ruff: noqa: RUF022 (__all__ is grouped by role, not sorted) __all__ = [ "__version__", # Pipeline @@ -23,15 +27,11 @@ # Wrappers (advanced / custom-pipeline use) "adjust_combat", "adjust_limma", - # Config + # Config and results "HarmonizeConfig", + "HarmonizeResult", + # Warnings + "InputScaleWarning", ] -# --------------------------------------------------------------------------- -# Semi-public API, importable from submodules for custom pipelines: -# harmonizepy.sorting.sort_batches -# harmonizepy.blocking.build_block_list -# harmonizepy.affiliation.remove_unique_combinations -# --------------------------------------------------------------------------- - -__version__ = "0.3.2" +__version__ = "0.4.0" diff --git a/src/harmonizepy/__main__.py b/src/harmonizepy/__main__.py index 3b732f2..f5587fa 100644 --- a/src/harmonizepy/__main__.py +++ b/src/harmonizepy/__main__.py @@ -15,20 +15,23 @@ import argparse import json import logging +import re import sys import tomllib from collections.abc import Sequence from importlib.metadata import version from pathlib import Path, PurePosixPath, PureWindowsPath -import numpy as np -import pandas as pd - -from .affiliation import build_affiliation_list -from .blocking import build_block_list -from .core import harmonize -from .io import read_description, read_main_data -from .validation import validate_data_matrix, validate_description, validate_harmonize_args +from .core import harmonize, plan_affiliations, prepare_inputs, resolve_needed_values +from .io import ( + _read_data_matrix, + format_from_suffix, + read_description, + write_atomically, + write_frame, +) +from .types import HarmonizeResult +from .validation import sample_batch_map # --------------------------------------------------------------------------- # Constants @@ -37,16 +40,11 @@ _LOG_FORMAT = "%(levelname)s [harmonizepy] %(message)s" _FILE_LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" -_FORMATS = ("tsv", "csv", "parquet") +# Errors from reading, validating, correcting, or writing that end a run with +# exit code 1 and one ERROR line instead of a traceback. +_RUN_ERRORS = (ValueError, TypeError, KeyError, ImportError, OSError) -# Map file extensions to output formats. Anything unrecognised falls back to tsv. -_EXT_TO_FMT: dict[str, str] = { - ".tsv": "tsv", - ".txt": "tsv", - ".csv": "csv", - ".parquet": "parquet", - ".pq": "parquet", -} +_FORMATS = ("tsv", "csv", "parquet") # Config keys that map directly to CLI flag destinations _VALID_CONFIG_KEYS: frozenset[str] = frozenset( @@ -60,6 +58,7 @@ "output", "output_format", "summary", + "report", } ) @@ -72,7 +71,7 @@ def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="harmonizepy", description=( - "Batch-effect harmonization for mass-spectrometry proteomics data.\n" + "Batch-effect correction for omics matrices with missing values.\n" "Wraps ComBat (parametric / non-parametric) and limma::removeBatchEffect.\n" ), formatter_class=argparse.RawDescriptionHelpFormatter, @@ -93,27 +92,34 @@ def _build_parser() -> argparse.ArgumentParser: ), ) - # -- Positional inputs -------------------------------------------------- parser.add_argument( "data", - help="Features x samples matrix (TSV, first column = feature identifiers).", + help=( + "Features x samples matrix of log-transformed values: TSV (default), CSV " + "(.csv) with feature names in the first column, or Parquet (.parquet, .pq) " + "with feature names as the index." + ), ) parser.add_argument( "description", - help="Batch description (CSV with columns: ID, sample, batch).", + help=( + "Batch description (CSV with columns ID, sample, batch; sample is not read). " + "Without the names ID and batch, the first column holds the sample IDs and " + "the third the batches." + ), ) - # -- Output ------------------------------------------------------------- parser.add_argument( "-o", "--output", default=None, metavar="PATH", help=( - "Output file path. Default: _corrected.tsv placed next to the " - "input data file. If --output-format parquet is given without -o, the default " - "becomes _corrected.parquet. Format is inferred from the extension " - "(.tsv, .csv, .parquet/.pq) unless --output-format is given." + "Output file path. Default: _corrected next to the input data " + "file, with the extension of --output-format (.tsv by default, .csv, or " + ".parquet). The format follows the extension (.csv, .parquet or .pq; any " + "other extension, such as .tsv or .txt, writes TSV) unless --output-format " + "is given." ), ) parser.add_argument( @@ -128,15 +134,14 @@ def _build_parser() -> argparse.ArgumentParser: ), ) - # -- Algorithm ---------------------------------------------------------- parser.add_argument( "--algorithm", choices=("ComBat", "limma"), default="ComBat", help=( - "Batch correction algorithm. " - "ComBat (default): empirical Bayes shrinkage, robust to small batches. " - "limma: linear-model residuals, faster, less aggressive correction." + "Correction engine. ComBat (default): location and scale per batch with " + "empirical-Bayes shrinkage across features. limma: removes the batch " + "means of each feature with a linear model, without shrinkage." ), ) parser.add_argument( @@ -146,11 +151,10 @@ def _build_parser() -> argparse.ArgumentParser: default=1, metavar="{1,2,3,4}", help=( - "ComBat variant (ignored when --algorithm limma). " - "1 = parametric, location + scale (default, best for most datasets). " - "2 = parametric, location only (no variance correction). " - "3 = non-parametric, location + scale (use for very small batches, n < 10). " - "4 = non-parametric, location only." + "ComBat mode (ignored with --algorithm limma): 1 = parametric prior, " + "location and scale (default); 2 = parametric prior, location only; " + "3 = non-parametric prior, location and scale; 4 = non-parametric prior, " + "location only." ), ) parser.add_argument( @@ -159,26 +163,23 @@ def _build_parser() -> argparse.ArgumentParser: default=None, metavar="N", help=( - "Minimum non-missing values a feature must have in every batch it enters. " - "Default: auto, 2 for ComBat modes 1/3 and limma (parametric estimators " - "need ≥ 2 observations); 1 for modes 2/4 (non-parametric can handle " - "single observations). Override only if you have specific quality requirements." + "Minimum observed values a feature needs in a batch for that batch to count " + "in its affiliation. Default: 2 for limma and ComBat modes 1 and 3, which " + "estimate a variance per batch; 1 for the location-only modes 2 and 4." ), ) - # -- Sorting and blocking ----------------------------------------------- parser.add_argument( "--sort", choices=("sparsity", "jaccard", "seriation"), default=None, metavar="{sparsity,jaccard,seriation}", help=( - "Sort batches before blocking so dissimilar batches are not grouped together. " - "sparsity: order by missing-value fraction (fastest, good default when sorting). " - "jaccard: pairwise feature-overlap similarity (more accurate). " - "seriation: optimal leaf ordering via hierarchical clustering (slowest, most " - "accurate for many batches). " - "No effect when --block is omitted." + "Order the batches before blocking so that similar batches share a block. " + "sparsity: batches with more present features first. jaccard: a chain of " + "batches by the overlap of their present features. seriation: the first " + "principal component of the batches' presence vectors. No effect without " + "--block." ), ) parser.add_argument( @@ -187,35 +188,43 @@ def _build_parser() -> argparse.ArgumentParser: default=None, metavar="N", help=( - "Group N consecutive (optionally sorted) batches into one sub-matrix block. " - "Must be ≥ 2 and < total number of batches. " - "Reduces memory usage and improves correction for datasets with many batches " - "(≥ 5). Omit (default) to process all batches together." + "Group N neighbouring batches (in --sort order) into one block when forming " + "the sub-matrices; the engines still correct each batch. N must be at least " + "2 and below the number of batches. Default: each batch is its own block." ), ) - # -- Feature handling --------------------------------------------------- parser.add_argument( "--unique-removal", action=argparse.BooleanOptionalAction, default=True, help=( - "Rescue features whose batch-presence pattern is unique (a singleton) by " - "cropping to the nearest shared pattern before correction. " - "Enabled by default; keeps more features in the output. " - "Disable only if you want strict pattern matching (--no-unique-removal)." + "Move a feature whose affiliation no other feature shares into the longest " + "affiliation of another feature within its own, as HarmonizR's ur = TRUE does; it then " + "loses the values of the dropped blocks but is corrected with others. " + "On by default; --no-unique-removal leaves such features raw." ), ) - # -- Workflow helpers --------------------------------------------------- parser.add_argument( "--summary", default=None, metavar="PATH", help=( - "Write a JSON run summary to PATH after completion. " - "Contains all resolved parameters, input/output dimensions, and the " - "package version, useful for reproducibility and lab notebooks." + "Write a JSON run summary to PATH after completion: the resolved " + "parameters, input and output dimensions, and the package version." + ), + ) + parser.add_argument( + "--report", + default=None, + metavar="PATH", + help=( + "Write a per-feature report to PATH: the status of each feature " + "(corrected, left raw and why, or missing), the batches its correction " + "used, its group size, whether unique removal cropped it, and how many " + "repeats of it were removed. The format follows the extension (.csv, " + ".parquet or .pq, otherwise TSV)." ), ) parser.add_argument( @@ -224,8 +233,9 @@ def _build_parser() -> argparse.ArgumentParser: help=( "Load and validate inputs, resolve all parameters, print a run plan, " "then exit without running correction. " - "Exit code 0 if inputs are valid, 1 on validation error. " - "Use in pipeline pre-checks to catch problems before committing compute time." + "Exit code 0 if inputs are valid, 1 on a validation error, 2 on a usage error " + "or a missing input file. Writes no files; cannot be combined with --log-file, " + "--summary, --json, or --report." ), ) parser.add_argument( @@ -233,11 +243,11 @@ def _build_parser() -> argparse.ArgumentParser: default=None, metavar="PATH", help=( - "Path to a TOML, JSON, or YAML (.yaml/.yml) config file. " - "Keys map 1:1 to CLI flag names (algorithm, combat_mode, needed_values, " - "sort, block, unique_removal, output, output_format, summary). " - "CLI flags override config file values; config file overrides built-in defaults. " - "YAML requires pyyaml; TOML requires Python ≥ 3.11 or tomli on older versions." + "Path to a TOML, JSON, or YAML (.yaml/.yml) config file. Keys are the " + "option names with underscores: algorithm, combat_mode, needed_values, " + "sort, block, unique_removal, output, output_format, summary, report. Options on " + "the command line override the file, and the file overrides the defaults. " + "YAML needs pyyaml (pip install harmonizepy[config])." ), ) parser.add_argument( @@ -245,13 +255,11 @@ def _build_parser() -> argparse.ArgumentParser: action="store_true", dest="json_output", help=( - "Print the run summary as JSON to stdout after completion. " - "For programmatic consumption: pipe to jq or capture in a shell script. " - "Suppresses INFO log messages so stdout contains only the JSON object." + "Print the run summary as JSON to stdout after completion. INFO log " + "messages are held back, so stdout holds only the JSON object." ), ) - # -- Verbosity ---------------------------------------------------------- verbosity = parser.add_mutually_exclusive_group() verbosity.add_argument( "-v", @@ -266,7 +274,6 @@ def _build_parser() -> argparse.ArgumentParser: help="Suppress all progress messages; only warnings and errors are shown.", ) - # -- Log file (optional override / disable) ----------------------------- parser.add_argument( "--log-file", default=None, @@ -284,7 +291,6 @@ def _build_parser() -> argparse.ArgumentParser: "written alongside the output with full DEBUG information.", ) - # -- Version ------------------------------------------------------------ parser.add_argument( "--version", action="version", @@ -302,24 +308,23 @@ def _build_parser() -> argparse.ArgumentParser: def _resolve_output_path( data_path: str, output: str | None, output_format: str | None = None ) -> str: - """Return an output path based on explicit args or CLI defaults. + """Return the output path: ``-o`` when given, otherwise a default. - Without ``-o``, the default path is ``_corrected.tsv`` next to the - input data file. When ``--output-format parquet`` is given without ``-o``, - the default path becomes ``_corrected.parquet``. + The default is ``_corrected`` next to the input data file, with the + extension of ``--output-format`` (``.tsv`` by default, ``.csv``, or + ``.parquet``). The caller's path style is kept: a path with a backslash or + a drive letter is treated as a Windows path, any other as a POSIX path, so + POSIX paths stay unchanged on Windows. """ if output is not None: return output - # Preserve the path style supplied by the caller. This keeps POSIX-style - # paths stable when the CLI is exercised on Windows, while retaining - # native drive/backslash formatting for regular Windows paths. path_type = ( PureWindowsPath - if "\\" in data_path or (len(data_path) > 1 and data_path[1] == ":") + if "\\" in data_path or re.match(r"[A-Za-z]:([\\/]|$)", data_path) else PurePosixPath ) p = path_type(data_path) - ext = ".parquet" if output_format == "parquet" else ".tsv" + ext = {"csv": ".csv", "parquet": ".parquet"}.get(output_format or "tsv", ".tsv") return str(p.parent / f"{p.stem}_corrected{ext}") @@ -327,7 +332,7 @@ def _infer_format(path: str, fmt_arg: str | None) -> str: """Determine write format from the explicit flag, then from file extension, then tsv.""" if fmt_arg is not None: return fmt_arg - return _EXT_TO_FMT.get(Path(path).suffix.lower(), "tsv") + return format_from_suffix(path) def _resolve_log_path(output_path: str) -> str: @@ -345,13 +350,20 @@ def _resolve_log_path(output_path: str) -> str: def _load_config(path: str) -> dict[str, object]: - """Load a TOML, JSON, or YAML config file and return the parsed mapping. - - Supported formats - ----------------- - ``.json`` (stdlib, always available) - ``.toml`` (stdlib ``tomllib``) - ``.yaml``/``.yml`` (requires ``pyyaml``: ``pip install pyyaml``) + """Return the mapping in a TOML, JSON, or YAML config file. + + JSON and TOML are read with the standard library; YAML (``.yaml``, + ``.yml``) needs ``pyyaml``. + + Raises + ------ + ValueError + If the suffix is not one of these, the file does not parse, or its top + level is not a mapping. + ImportError + If a YAML file is given and ``pyyaml`` is not installed. + OSError + If the file cannot be read. """ p = Path(path) ext = p.suffix.lower() @@ -367,20 +379,23 @@ def _load_config(path: str) -> dict[str, object]: elif ext in (".yaml", ".yml"): try: - import yaml # type: ignore[import-untyped] - except ImportError: + import yaml # type: ignore[import-untyped] # pyyaml ships no type stubs + except ImportError as error: raise ImportError( "YAML config requires 'pyyaml': pip install harmonizepy[config]" - ) from None + ) from error with p.open(encoding="utf-8") as fh: - raw = yaml.safe_load(fh) + try: + raw = yaml.safe_load(fh) + except yaml.YAMLError as error: + raise ValueError(f"invalid YAML in config file '{path}': {error}") from error else: raise ValueError(f"Unsupported config format '{ext}'. Use .toml, .json, .yaml, or .yml.") if not isinstance(raw, dict): raise ValueError(f"Config file must be a TOML/JSON/YAML mapping, got {type(raw).__name__}.") - return raw # type narrowed to dict[Any, Any] by isinstance check above + return raw # --------------------------------------------------------------------------- @@ -388,20 +403,6 @@ def _load_config(path: str) -> dict[str, object]: # --------------------------------------------------------------------------- -def _write_result(df: pd.DataFrame, path: str, fmt: str) -> None: - """Write *df* in the requested format.""" - if fmt == "csv": - df.to_csv(path) - elif fmt == "parquet": - from .io import _HAVE_PYARROW - - if not _HAVE_PYARROW: - raise ImportError("Parquet output requires pyarrow: pip install harmonizepy[io]") - df.to_parquet(path, index=True, engine="pyarrow") - else: - df.to_csv(path, sep="\t") - - def _build_summary_dict( *, data_file: str, @@ -410,7 +411,7 @@ def _build_summary_dict( output_format: str, algorithm: str, combat_mode: int, - needed_values: int | None, + needed_values: int, sort: str | None, block: int | None, unique_removal: bool, @@ -428,7 +429,7 @@ def _build_summary_dict( "output_format": output_format, "algorithm": algorithm, "combat_mode": combat_mode, - "needed_values": needed_values, # None = auto-selected inside harmonize + "needed_values": needed_values, "sort_strategy": sort, "block_size": block, "unique_removal": unique_removal, @@ -440,9 +441,9 @@ def _build_summary_dict( def _write_summary(path: str, summary: dict[str, object]) -> None: - """Write a JSON run-summary file to *path*.""" - with Path(path).open("w", encoding="utf-8") as fh: - json.dump(summary, fh, indent=2) + """Write a JSON run-summary file to *path*, atomically (``write_atomically``).""" + text = json.dumps(summary, indent=2) + write_atomically(path, lambda tmp: Path(tmp).write_text(text, encoding="utf-8")) logging.getLogger("harmonizepy").info("Run summary written to %s", path) @@ -459,7 +460,7 @@ def _print_dry_run( output_format: str, algorithm: str, combat_mode: int, - needed_values: int | None, + needed_values: int, sort: str | None, block: int | None, unique_removal: bool, @@ -469,12 +470,12 @@ def _print_dry_run( n_submatrices: int, ) -> None: """Print a human-readable dry-run summary to stdout.""" - nv_str = "auto" if needed_values is None else str(needed_values) + nv_str = str(needed_values) sort_str = sort or "none" - block_str = str(block) if block is not None else "none (all batches in one group)" + block_str = str(block) if block is not None else "none (each batch is its own block)" ur_str = "enabled" if unique_removal else "disabled" algo_str = f"{algorithm} mode {combat_mode}" if algorithm == "ComBat" else algorithm - rule = "─" * 52 + rule = "-" * 52 lines = [ "", @@ -507,11 +508,26 @@ def _print_dry_run( def main(argv: Sequence[str] | None = None) -> None: - """Parse arguments and run the harmonization pipeline.""" + """Run the ``harmonizepy`` command with *argv*, or ``sys.argv`` when ``None``. + + A config file's values become parser defaults, read with a pre-parser + before the full parse, so options given on the command line always win. + Shell completion is set up when ``argcomplete`` is installed. A dry run + refuses ``--log-file``, ``--summary``, ``--json``, and ``--report``, since it writes + nothing those options would shape. + + A correction run writes the corrected matrix, a log file next to it + unless ``--no-log`` (or at ``--log-file``), and the summary when + ``--summary`` is given, and the per-feature report when ``--report`` is + given; ``--json`` prints the summary to stdout. + + Exit codes: 0 on success; 1 on an input, correction, or output error, + reported as one ERROR line, including a value the parser accepts but the + library refuses (``--block 1``); 2 on a usage error, a config file error, + or a missing input file. + """ parser = _build_parser() - # Shell completion: silently skip when argcomplete is not installed. - # This is the standard optional-dependency pattern, not a bug swallow. try: import argcomplete @@ -519,10 +535,6 @@ def main(argv: Sequence[str] | None = None) -> None: except ImportError: pass - # -- Config file pre-parse: apply config values as parser defaults ------ - # Use a lightweight pre-parser so we can call parser.set_defaults() before - # the full parse. CLI flags always win because set_defaults() only affects - # the default value, not an explicitly supplied argument. _pre = argparse.ArgumentParser(add_help=False) _pre.add_argument("--config", default=None) _pre_ns, _ = _pre.parse_known_args(argv) @@ -536,18 +548,119 @@ def main(argv: Sequence[str] | None = None) -> None: _unknown = set(_cfg) - _VALID_CONFIG_KEYS if _unknown: parser.error(f"Unknown config key(s): {', '.join(sorted(_unknown))}") - parser.set_defaults(**{k: v for k, v in _cfg.items() if k in _VALID_CONFIG_KEYS}) + _cfg = _check_config_values(parser, _cfg) + given = parser.parse_args(argv) + parser.set_defaults(**_cfg) + else: + _cfg = {} args = parser.parse_args(argv) + if not _cfg: + given = args - # -- Resolve output path and format ------------------------------------- output_path = _resolve_output_path(args.data, args.output, args.output_format) output_fmt = _infer_format(output_path, args.output_format) - # -- Logging setup ------------------------------------------------------ - # Configure the root harmonizepy logger so all child modules - # (harmonizepy.combat, harmonizepy.core, etc.) inherit the settings. - # --json suppresses INFO so stdout contains only the JSON object. + if args.dry_run: + for flag, key in ( + ("--log-file", "log_file"), + ("--summary", "summary"), + ("--json", "json_output"), + ("--report", "report"), + ): + if getattr(given, key): + parser.error(f"{flag} cannot be used with --dry-run") + else: + if args.report is not None and not args.report: + parser.error("--report needs a file path") + _check_output_paths(parser, args, output_path) + + if not Path(args.data).is_file(): + parser.error(f"data file not found: '{args.data}'") + if not Path(args.description).is_file(): + parser.error(f"description file not found: '{args.description}'") + + package_logger = logging.getLogger("harmonizepy") + saved_level, saved_propagate = package_logger.level, package_logger.propagate + handlers = _configure_logging(args, output_path) + try: + if args.dry_run: + _run_dry_run(args, output_path, output_fmt, console=handlers[0]) + else: + _run_correction(args, output_path, output_fmt) + finally: + _detach_logging(handlers) + package_logger.setLevel(saved_level) + package_logger.propagate = saved_propagate + + +def _check_config_values( + parser: argparse.ArgumentParser, cfg: dict[str, object] +) -> dict[str, object]: + """Return the config values checked and converted as the matching flags would be. + + A value must have the flag's type and lie in its choices; an on/off flag + needs a boolean, and a path a string. A value that fails is a usage error + (exit code 2), as the same value given as a flag is. + """ + actions = {action.dest: action for action in parser._actions} + checked: dict[str, object] = {} + for key, value in cfg.items(): + action = actions[key] + if isinstance(action, argparse.BooleanOptionalAction): + if not isinstance(value, bool): + parser.error(f"config key '{key}' must be true or false, got {value!r}") + elif action.type is int: + if isinstance(value, str) and value.strip().lstrip("-").isdigit(): + value = int(value) + if not isinstance(value, int) or isinstance(value, bool): + parser.error(f"config key '{key}' must be a whole number, got {value!r}") + elif value is not None and not isinstance(value, str): + parser.error(f"config key '{key}' must be a string, got {value!r}") + if action.choices is not None and value not in action.choices: + choices = ", ".join(str(c) for c in action.choices) + parser.error(f"config key '{key}' must be one of {choices}, got {value!r}") + checked[key] = value + return checked + + +def _check_output_paths( + parser: argparse.ArgumentParser, args: argparse.Namespace, output_path: str +) -> None: + """Refuse a run whose output files would overwrite an input or each other. + + Covers the corrected matrix, the summary, the report, and the log file; + paths are compared after resolving them, so ``./data.tsv`` and ``data.tsv`` + are the same file. A refusal is a usage error (exit code 2). + """ + outputs = [("-o", output_path)] + if args.summary: + outputs.append(("--summary", args.summary)) + if args.report: + outputs.append(("--report", args.report)) + if not args.no_log: + outputs.append(("--log-file", args.log_file or _resolve_log_path(output_path))) + inputs = (("the data file", args.data), ("the description file", args.description)) + seen: dict[Path, str] = {} + for flag, path in outputs: + target = Path(path).resolve() + for name, other in inputs: + if target == Path(other).resolve(): + parser.error(f"{flag} would overwrite {name}: '{path}'") + if target in seen: + parser.error(f"{seen[target]} and {flag} name the same file: '{path}'") + seen[target] = flag + + +def _configure_logging(args: argparse.Namespace, output_path: str) -> list[logging.Handler]: + """Attach the console handler and, for a correction run, the log file handler. + + The console shows INFO by default, DEBUG with ``--verbose``, and WARNING with + ``--quiet`` or ``--json`` (so that stdout holds only the JSON object). The log + file, next to the output unless ``--log-file`` or ``--no-log`` is given, + records DEBUG with timestamps. A dry run writes no log file. The console + handler is first in the returned list. + """ if args.verbose: level = logging.DEBUG elif args.quiet or args.json_output: @@ -555,117 +668,107 @@ def main(argv: Sequence[str] | None = None) -> None: else: level = logging.INFO - root_logger = logging.getLogger("harmonizepy") - root_logger.setLevel(logging.DEBUG) - root_logger.propagate = False + package_logger = logging.getLogger("harmonizepy") + package_logger.setLevel(logging.DEBUG) + package_logger.propagate = False - # Terminal handler: clean format, no timestamps, respects --verbose/--quiet. console = logging.StreamHandler(sys.stderr) console.setLevel(level) console.setFormatter(logging.Formatter(_LOG_FORMAT)) - root_logger.addHandler(console) + package_logger.addHandler(console) + handlers: list[logging.Handler] = [console] - # File handler: always-on by default, writes DEBUG with timestamps. - # Log path is derived from the output path (e.g. corrected.tsv -> corrected.log) - # unless overridden via --log-file, or disabled via --no-log. - if not args.no_log: + if not args.no_log and not args.dry_run: log_path = args.log_file if args.log_file else _resolve_log_path(output_path) try: - fh = logging.FileHandler(log_path, mode="w", encoding="utf-8") - fh.setLevel(logging.DEBUG) - fh.setFormatter(logging.Formatter(_FILE_LOG_FORMAT)) - root_logger.addHandler(fh) + file_handler = logging.FileHandler(log_path, mode="w", encoding="utf-8") except OSError: - # If the log file cannot be created, warn and continue without it. - logging.getLogger("harmonizepy").warning( - "Could not create log file at %s; proceeding without file logging.", - log_path, + package_logger.warning( + "Could not create log file at %s; proceeding without file logging.", log_path ) + else: + file_handler.setLevel(logging.DEBUG) + file_handler.setFormatter(logging.Formatter(_FILE_LOG_FORMAT)) + package_logger.addHandler(file_handler) + handlers.append(file_handler) + return handlers - # -- File existence pre-check (fast fail before any loading) ------------ - if not Path(args.data).is_file(): - parser.error(f"data file not found: '{args.data}'") - if not Path(args.description).is_file(): - parser.error(f"description file not found: '{args.description}'") - # -- Dry-run path ------------------------------------------------------- - # Suppress pipeline logging during dry-run so the plan output is clean. - if args.dry_run: - _prev_level = console.level - console.setLevel(logging.WARNING) - try: - data = read_main_data(args.data) - description = read_description(args.description) - validate_data_matrix(data) - validate_description(description, data) - # Resolve n_batches so block_size can be validated properly - sample_to_batch = dict( - zip( - description.iloc[:, 0].astype(str), - description.iloc[:, 2].astype(int), - strict=True, - ) - ) - batch_arr = np.array([sample_to_batch[col] for col in data.columns], dtype=np.int64) - n_batches = int(np.unique(batch_arr).size) - # Resolve effective needed_values once for both validation and spotting - if args.needed_values is not None: - nv_eff = args.needed_values - elif args.algorithm == "limma" or args.combat_mode in (1, 3): - nv_eff = 2 - else: - nv_eff = 1 - validate_harmonize_args( - args.algorithm, - args.combat_mode, - nv_eff, - sort_strategy=args.sort, - block_size=args.block, - unique_removal=args.unique_removal, - n_batches=n_batches, - ) - # Build block list - if args.block is not None: - block_list = build_block_list(batch_arr, block_size=args.block) - else: - block_list = batch_arr.copy() - # Spot sub-matrices (no adjustment) - affiliation_list = build_affiliation_list(data, batch_arr, block_list, nv_eff) - n_submatrices = len({a for a in affiliation_list if len(a) > 0}) - except (ValueError, TypeError, KeyError) as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - finally: - console.setLevel(_prev_level) - - n_features, n_samples = data.shape - _print_dry_run( - data_file=args.data, - description_file=args.description, - output_file=output_path, - output_format=output_fmt, +def _detach_logging(handlers: list[logging.Handler]) -> None: + """Remove and close the handlers ``_configure_logging`` attached.""" + package_logger = logging.getLogger("harmonizepy") + for handler in handlers: + package_logger.removeHandler(handler) + handler.close() + + +def _run_dry_run( + args: argparse.Namespace, output_path: str, output_fmt: str, *, console: logging.Handler +) -> None: + """Validate the inputs, plan the groups as a correction run would, and print the plan. + + Pipeline log messages are held back to WARNING so that the plan is the only + output. Exits with code 1 and an ERROR line on an input error. + """ + previous_level = console.level + console.setLevel(logging.WARNING) + try: + inputs = prepare_inputs( + args.data, + args.description, algorithm=args.algorithm, combat_mode=args.combat_mode, needed_values=args.needed_values, sort=args.sort, block=args.block, unique_removal=args.unique_removal, - n_features=n_features, - n_samples=n_samples, - n_batches=n_batches, - n_submatrices=n_submatrices, ) - return # exit 0 implicitly, no correction performed + plan = plan_affiliations( + inputs.data, + inputs.batch_list, + sort=args.sort, + block=args.block, + needed_values=inputs.needed_values, + unique_removal=args.unique_removal, + ) + except _RUN_ERRORS as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + finally: + console.setLevel(previous_level) + + n_features, n_samples = inputs.data.shape + _print_dry_run( + data_file=args.data, + description_file=args.description, + output_file=output_path, + output_format=output_fmt, + algorithm=args.algorithm, + combat_mode=args.combat_mode, + needed_values=inputs.needed_values, + sort=args.sort, + block=args.block, + unique_removal=args.unique_removal, + n_features=n_features, + n_samples=n_samples, + n_batches=inputs.n_batches, + n_submatrices=plan.n_groups, + ) + - # -- Full pipeline run -------------------------------------------------- +def _run_correction(args: argparse.Namespace, output_path: str, output_fmt: str) -> None: + """Correct the data, write the output, and write or print the run summary. + + Exits with code 1 and an ERROR line when reading, validating, correcting, or + writing the output fails. A summary file that cannot be written gives a + WARNING line and does not change the exit code. + """ try: - data_df = read_main_data(args.data) + data_df = _read_data_matrix(args.data) description_df = read_description(args.description) - n_features_input, n_samples = data_df.shape - n_batches = int(description_df.iloc[:, 2].nunique()) - - result = harmonize( + n_batches = len(set(sample_batch_map(description_df).values())) + outcome = harmonize( data_df, description_df, algorithm=args.algorithm, @@ -674,48 +777,56 @@ def main(argv: Sequence[str] | None = None) -> None: sort=args.sort, block=args.block, unique_removal=args.unique_removal, + return_report=args.report is not None, ) - except (ValueError, TypeError, KeyError) as exc: + if isinstance(outcome, HarmonizeResult): + result, report = outcome.data, outcome.report + else: + result, report = outcome, None + except _RUN_ERRORS as exc: print(f"ERROR: {exc}", file=sys.stderr) sys.exit(1) - # -- Write output ------------------------------------------------------- try: - _write_result(result, output_path, output_fmt) - except Exception as exc: + write_frame(result, output_path, output_fmt) + except _RUN_ERRORS as exc: print(f"ERROR writing output to '{output_path}': {exc}", file=sys.stderr) sys.exit(1) - logging.getLogger("harmonizepy").info("Output written to %s", output_path) - # -- Run summary (--summary file and/or --json stdout) ------------------ - if args.summary or args.json_output: - _summary = _build_summary_dict( - data_file=args.data, - description_file=args.description, - output_file=output_path, - output_format=output_fmt, - algorithm=args.algorithm, - combat_mode=args.combat_mode, - needed_values=args.needed_values, - sort=args.sort, - block=args.block, - unique_removal=args.unique_removal, - n_features_input=n_features_input, - n_features_output=result.shape[0], - n_samples=n_samples, - n_batches=n_batches, - ) - if args.summary: - try: - _write_summary(args.summary, _summary) - except OSError as exc: - print( - f"WARNING: could not write summary to '{args.summary}': {exc}", - file=sys.stderr, - ) - if args.json_output: - print(json.dumps(_summary, indent=2)) + if report is not None: + try: + write_frame(report, args.report, format_from_suffix(args.report)) + except _RUN_ERRORS as exc: + print(f"ERROR writing report to '{args.report}': {exc}", file=sys.stderr) + sys.exit(1) + logging.getLogger("harmonizepy").info("Report written to %s", args.report) + + if not (args.summary or args.json_output): + return + summary = _build_summary_dict( + data_file=args.data, + description_file=args.description, + output_file=output_path, + output_format=output_fmt, + algorithm=args.algorithm, + combat_mode=args.combat_mode, + needed_values=resolve_needed_values(args.algorithm, args.combat_mode, args.needed_values), + sort=args.sort, + block=args.block, + unique_removal=args.unique_removal, + n_features_input=n_features_input, + n_features_output=result.shape[0], + n_samples=n_samples, + n_batches=n_batches, + ) + if args.summary: + try: + _write_summary(args.summary, summary) + except OSError as exc: + print(f"WARNING: could not write summary to '{args.summary}': {exc}", file=sys.stderr) + if args.json_output: + print(json.dumps(summary, indent=2)) if __name__ == "__main__": diff --git a/src/harmonizepy/affiliation.py b/src/harmonizepy/affiliation.py index 633f709..ed21da6 100644 --- a/src/harmonizepy/affiliation.py +++ b/src/harmonizepy/affiliation.py @@ -1,18 +1,18 @@ -"""Affiliation logic: build and reduce per-feature batch affiliations. - -The affiliation list records, for each feature (row), which blocks have -sufficient non-missing data. ``reduce_to_unique_groups`` then collapses -features sharing identical affiliations into groups so that -``splitting.py`` can extract one sub-matrix per group. - -In the R HarmonizR source, ``unique()`` on the affiliation list *is* the -binary reduction step - there is no separate operation. This module -combines both responsibilities. +"""Affiliations: the blocks in which each feature has enough values. + +A feature's affiliation is the sorted tuple of block labels in which every +batch holds at least ``needed_values`` observed values of the feature. +Features with the same affiliation form a group, and each group is corrected +as one sub-matrix. Unique removal moves a feature whose affiliation no other +feature shares into the longest affiliation of another feature that lies +within its own, as R HarmonizR's ``ur = TRUE`` does. """ from __future__ import annotations import logging +from collections import Counter +from collections.abc import Mapping import numpy as np import numpy.typing as npt @@ -26,11 +26,10 @@ def _assemble_affiliations( block_oks: list[npt.NDArray[np.bool_]], n_features: int, ) -> list[tuple[int, ...]]: - """Assemble per-feature affiliation tuples from per-block masks. + """Return one affiliation tuple per feature from the per-block masks. - Repeated block-membership patterns are common on fragmented datasets, so - cache the tuple reconstruction by mask pattern instead of rebuilding the - same Python tuple for every matching feature. + Features often share a pattern, so each distinct pattern is turned into a + tuple once: by a bit code for up to 64 blocks, by packed bytes beyond. """ if not block_oks: return [()] * n_features @@ -82,56 +81,59 @@ def build_affiliation_list( *, data_np: npt.NDArray[np.float64] | None = None, ) -> list[tuple[int, ...]]: - """Determine per-feature batch/block affiliation. + """Return each feature's affiliation: the blocks where it has enough values. - For each feature (row), identifies the blocks where the feature has - at least *needed_values* non-missing observations in every original - batch contained within that block. + A block counts for a feature when every batch inside the block holds at + least *needed_values* observed values of it. Parameters ---------- data : DataFrame - Features x samples matrix (may contain NaN). + Features x samples matrix; missing cells are allowed. batch_list : ndarray, shape (n_samples,) - Integer batch label per sample. + Batch label of each column. block_list : ndarray, shape (n_samples,) - Integer block label per sample (equals *batch_list* when no - blocking is applied). + Block label of each column; equal to *batch_list* without blocking. needed_values : int - Minimum non-NA values per batch within a block. - data_np : ndarray or None, keyword-only - Optional precomputed float64 view or copy of *data* with shape - ``(n_features, n_samples)``. When provided, reused instead of - converting *data* again inside this function. + Minimum observed values per batch. + data_np : ndarray, shape (n_features, n_samples), optional + *data* as float64, reused instead of converting *data* again. Returns ------- - list[tuple[int, ...]] - One tuple per feature. Each tuple contains the sorted block IDs - where the feature has sufficient data. An empty tuple means - the feature has insufficient data everywhere. + list of tuple of int + One sorted tuple of block labels per feature, in row order. An empty + tuple means no block qualifies. Raises ------ ValueError - Propagated from NumPy if *batch_list* or *block_list* cannot be - broadcast against the columns of *data*. + If *batch_list* or *block_list* does not have one label per column. Examples -------- + The second feature has one value in batch 2, below ``needed_values=2``: + >>> import numpy as np, pandas as pd >>> from harmonizepy.affiliation import build_affiliation_list - >>> data = pd.DataFrame({"s1": [1.0, np.nan], "s2": [2.0, 3.0], "s3": [4.0, 5.0]}) - >>> batch = np.array([1, 1, 2]) - >>> build_affiliation_list(data, batch, batch, needed_values=1) - [(1, 2), (2,)] + >>> data = pd.DataFrame( + ... {"s1": [1.0, 2.0], "s2": [1.5, 2.5], "s3": [3.0, np.nan], "s4": [3.5, 4.0]} + ... ) + >>> batch = np.array([1, 1, 2, 2]) + >>> build_affiliation_list(data, batch, batch, needed_values=2) + [(1, 2), (1,)] """ batch_arr = np.asarray(batch_list) block_arr = np.asarray(block_list) + n_samples = data.shape[1] + if batch_arr.shape != (n_samples,) or block_arr.shape != (n_samples,): + raise ValueError( + f"batch_list and block_list need one label per column ({n_samples}); " + f"got {batch_arr.shape} and {block_arr.shape}." + ) unique_blocks = np.unique(block_arr) - # Pre-compute: for each block, the sample indices per original batch block_info: list[list[np.ndarray]] = [] for blk in unique_blocks: blk_mask = block_arr == blk @@ -143,10 +145,6 @@ def build_affiliation_list( data_np = data.to_numpy(dtype=np.float64) notna = ~np.isnan(data_np) - - # Vectorised per-block check across all features at once. - # For each block, compute a boolean array indicating whether each - # feature has >= needed_values non-NA in every batch within that block. block_oks: list[np.ndarray] = [] for batch_indices in block_info: batch_oks = [notna[:, idx].sum(axis=1) >= needed_values for idx in batch_indices] @@ -168,24 +166,18 @@ def build_affiliation_list( def reduce_to_unique_groups( affiliation_list: list[tuple[int, ...]], ) -> dict[tuple[int, ...], list[int]]: - """Group feature indices by their shared affiliation pattern. + """Group feature row indices by affiliation. Parameters ---------- - affiliation_list : list[tuple[int, ...]] - One tuple per feature from ``build_affiliation_list``. + affiliation_list : list of tuple of int + One affiliation per feature, as ``build_affiliation_list`` returns. Returns ------- - dict[tuple[int, ...], list[int]] - Mapping from each unique affiliation to the list of feature - row indices that share it. Iteration order matches first - appearance. - - Raises - ------ - TypeError - If *affiliation_list* contains non-hashable elements. + dict + Each distinct affiliation, in order of first appearance, mapped to the + row indices of the features that have it, in row order. Examples -------- @@ -202,98 +194,91 @@ def reduce_to_unique_groups( def remove_unique_combinations( affiliation_list: list[tuple[int, ...]], + batches_per_block: Mapping[int, int] | None = None, ) -> list[tuple[int, ...]]: - """Rescue singleton features by cropping their affiliation to a shared pattern. - - A feature whose batch-presence combination is unique (no other feature - shares it) would end up alone in a sub-matrix. ComBat and limma cannot - adjust a single feature, so it would otherwise be dropped. - - For each such singleton, this function finds the closest non-unique - affiliation (the one reachable by removing the fewest batches) and - replaces the singleton's affiliation with that pattern. Empty - affiliations (features with no data anywhere) are left unchanged. - - This mirrors R ``HarmonizR:::unique_removal`` (``ur`` parameter, - default ``TRUE`` in R HarmonizR v1.8.0). + """Move each feature with an affiliation of its own into another feature's. + + A feature whose affiliation no other feature shares would form a group of + one, which is returned with its raw values. This step moves such a feature + into the longest affiliation of another feature that is a proper subset of + its own; the feature then loses the values in the dropped blocks but is + corrected with others. As in HarmonizR's ``ur`` option, the target may + itself be held by a single feature, which then keeps its affiliation and + shares it. + + Features are taken longest affiliation first, so the order of the rows + does not matter. Among equally long targets, the one more features hold + wins, then the smallest tuple. An affiliation that spans a single batch is + never a target: its group is left raw, so the move would only discard the + feature's other values. A feature with no target keeps its affiliation and + its values; HarmonizR empties it instead. Parameters ---------- - affiliation_list : list[tuple[int, ...]] - One tuple per feature from ``build_affiliation_list``. - Each tuple contains sorted block IDs where the feature has - sufficient data. + affiliation_list : list of tuple of int + One affiliation per feature, as ``build_affiliation_list`` returns. + batches_per_block : mapping of int to int or None + The number of batches in each block, to tell which affiliations span a + single batch. ``None`` counts each block as one batch, which is exact + without blocking. Returns ------- - list[tuple[int, ...]] - New affiliation list of the same length. Singleton tuples are - replaced with a subset of their original blocks that at least one - other feature also shares. Non-singleton and empty tuples are - unchanged. - - Raises - ------ - ValueError - If all non-empty affiliations are unique (no shared pattern exists - to crop to). This indicates a dataset too fragmented for unique - removal to help. In practice this cannot happen when n_features > 1. + list of tuple of int + A new list of the same length; the input is not modified. Examples -------- + The first two features each have an affiliation of their own. The first + moves into the second's, which keeps it: + >>> from harmonizepy.affiliation import remove_unique_combinations - >>> # Feature 0 is a singleton; features 1 and 2 share (1, 2) - >>> result = remove_unique_combinations([(1, 2, 3), (1, 2), (1, 2)]) - >>> result[0] # cropped to the nearest shared pattern - (1, 2) - >>> result[1:] # unchanged - [(1, 2), (1, 2)] + >>> remove_unique_combinations([(1, 2, 3), (1, 2), (4, 5), (4, 5)]) + [(1, 2), (1, 2), (4, 5), (4, 5)] """ result = list(affiliation_list) - - # Count how many features share each non-empty affiliation - counts: dict[tuple[int, ...], int] = {} - for affil in result: - if affil: - counts[affil] = counts.get(affil, 0) + 1 - - # Collect the non-unique (shared) patterns used as rescue targets - non_unique = {affil for affil, cnt in counts.items() if cnt > 1} - - if not non_unique: - logger.debug("No shared patterns available for rescue") - return result - + counts = Counter(affil for affil in result if affil) + + def n_batches(pattern: tuple[int, ...]) -> int: + if batches_per_block is None: + return len(pattern) + return sum(batches_per_block.get(block, 1) for block in pattern) + + sets = {pattern: frozenset(pattern) for pattern in counts} + by_length: dict[int, list[tuple[int, ...]]] = {} + for pattern in counts: + if n_batches(pattern) >= 2: + by_length.setdefault(len(pattern), []).append(pattern) + lengths = sorted(by_length, reverse=True) + + unique = sorted( + ((affil, i) for i, affil in enumerate(result) if affil and counts[affil] == 1), + key=lambda item: (-len(item[0]), item[0]), + ) + holder = dict(unique) + kept: set[int] = set() rescued = 0 - for i, affil in enumerate(result): - if not affil or affil in non_unique: + for own, i in unique: + if i in kept: continue - - best = _find_best_crop(frozenset(affil), non_unique) - if best is not None: - result[i] = best - rescued += 1 - - if rescued > 0: - logger.debug("Unique removal rescued %d feature(s)", rescued) + own_set = sets[own] + target = None + for length in lengths: + if length >= len(own): + continue + candidates = [p for p in by_length[length] if counts[p] > 0 and sets[p] < own_set] + if candidates: + target = max(candidates, key=lambda p: (counts[p], tuple(-b for b in p))) + break + if target is None: + continue + if counts[target] == 1: + kept.add(holder[target]) + counts[own] -= 1 + counts[target] += 1 + result[i] = target + rescued += 1 + + if rescued: + logger.debug("Unique removal moved %d feature(s)", rescued) return result - - -def _find_best_crop( - affil_set: frozenset[int], - non_unique: set[tuple[int, ...]], -) -> tuple[int, ...] | None: - """Return the largest subset of *affil_set* that is in *non_unique*. - - Iterates over the non-unique patterns directly rather than generating - all subsets of *affil_set*. For datasets with few non-unique patterns - and long affiliations this is orders of magnitude faster. - - Returns ``None`` if no non-empty subset matches. - """ - best = None - for pattern in non_unique: - if set(pattern).issubset(affil_set) and len(pattern) < len(affil_set): - if best is None or len(pattern) > len(best): - best = pattern - return best diff --git a/src/harmonizepy/blocking.py b/src/harmonizepy/blocking.py index 48e77e5..ef893ef 100644 --- a/src/harmonizepy/blocking.py +++ b/src/harmonizepy/blocking.py @@ -1,15 +1,9 @@ -"""Batch blocking: group neighboring batches into superblocks. +"""Blocks: groups of neighbouring batches used to form the sub-matrices. -Blocking collapses *N* consecutive batches into a single block ID for -the purpose of dissection (deciding which samples enter which sub-matrix -during splitting). It is purely a indexing operation. The original -``batch_list`` is kept unchanged and still drives the ComBat/limma -adjustment step. - -When no blocking is requested, ``block_list == batch_list`` and no code -in this module is needed. - -This mirrors R ``HarmonizR:::blocking``. +A block label replaces the batch label only when affiliations and +sub-matrices are formed; the engines still correct each original batch. +Without blocking, the block list is the batch list. This follows R +``HarmonizR:::blocking``. """ from __future__ import annotations @@ -26,47 +20,40 @@ def build_block_list( batch_list: npt.NDArray[np.integer], block_size: int, ) -> npt.NDArray[np.integer]: - """Map each sample to a block ID by grouping neighbouring batches. - - Batches appear in the order they are first encountered in - *batch_list*. Every *block_size* consecutive unique batches are - assigned the same block ID. If the total number of unique batches is - not evenly divisible by *block_size*, the trailing remainder batches - form a smaller final block. + """Return the block label of each sample, grouping neighbouring batches. - The returned array has the same length and dtype as *batch_list* and - is 1-indexed (block IDs start at 1) to match R's convention. + Batches are taken in order of first appearance, and every *block_size* + of them share a block. When the number of batches is not a multiple of + *block_size*, the last block is smaller. Block labels start at 1, as in R. Parameters ---------- batch_list : ndarray, shape (n_samples,) - Integer batch label per sample. The unique values, taken in - first-appearance order, define the batch sequence that is - partitioned into blocks. + Batch label of each sample. block_size : int - Number of consecutive unique batches per block. Must be >= 2 - and < the number of unique batches (a block size >= n_batches - would merge all batches into one block, making adjustments - impossible). + Batches per block: at least 2 and fewer than the number of batches, + since one block holding every batch would leave nothing to correct. Returns ------- - ndarray, shape (n_samples,), dtype same as *batch_list* - Block label per sample. + ndarray, shape (n_samples,) + Block label of each sample, with the dtype of *batch_list*. Raises ------ ValueError - If *block_size* < 2 or *block_size* >= number of unique batches. + If *block_size* is below 2 or not below the number of batches. Examples -------- + With four batches and blocks of three, the fourth batch forms a block alone: + >>> import numpy as np >>> from harmonizepy.blocking import build_block_list >>> batch = np.array([1, 1, 2, 2, 3, 3, 4, 4]) >>> build_block_list(batch, block_size=2) array([1, 1, 1, 1, 2, 2, 2, 2]) - >>> build_block_list(batch, block_size=3) # remainder: batch 4 alone + >>> build_block_list(batch, block_size=3) array([1, 1, 1, 1, 1, 1, 2, 2]) """ batch_arr = np.asarray(batch_list) @@ -84,19 +71,19 @@ def build_block_list( f"because every feature would be in a single group." ) - # Assign each unique batch to a block index (0-based), then +1 for 1-indexing - batch_to_block = {int(bid): i // block_size + 1 for i, bid in enumerate(unique_batches)} - - block_arr = np.vectorize(batch_to_block.__getitem__)(batch_arr).astype(batch_arr.dtype) + _, first_index, inverse = np.unique(batch_arr, return_index=True, return_inverse=True) + rank_by_first_appearance = np.argsort(np.argsort(first_index, kind="stable"), kind="stable") + block_of_label = rank_by_first_appearance // block_size + 1 + block_arr: npt.NDArray[np.integer] = block_of_label[inverse].astype(batch_arr.dtype) - n_blocks = int(block_arr[-1]) + n_blocks = len(np.unique(block_arr)) logger.debug( "Built %d blocks of size %d from %d batches", n_blocks, block_size, n_batches, ) - return block_arr # type: ignore[no-any-return] + return block_arr # --------------------------------------------------------------------------- @@ -104,13 +91,6 @@ def build_block_list( # --------------------------------------------------------------------------- -def _unique_ordered(arr: npt.NDArray[np.integer]) -> list[int]: - """Return unique values from *arr* in first-appearance order.""" - seen: set[int] = set() - result: list[int] = [] - for v in arr: - iv = int(v) - if iv not in seen: - seen.add(iv) - result.append(iv) - return result +def _unique_ordered(arr: npt.NDArray[np.generic]) -> list[object]: + """Return the distinct values of *arr* in order of first appearance.""" + return list(dict.fromkeys(arr.tolist())) diff --git a/src/harmonizepy/combat.py b/src/harmonizepy/combat.py index 9389b4f..caedc4e 100644 --- a/src/harmonizepy/combat.py +++ b/src/harmonizepy/combat.py @@ -1,9 +1,8 @@ -"""Empirical Bayes batch-effect correction (ComBat). +"""Empirical-Bayes batch-effect correction (ComBat) in NumPy. -Pure NumPy re-implementation of the Johnson, Li & Rabinovic (2007) -algorithm [1]_ with full vectorisation and no legacy ``np.matrix`` usage. - -Four modes are supported, matching R ``sva::ComBat`` conventions: +The method of Johnson, Li and Rabinovic (2007) [1]_, following R +``sva::ComBat`` 3.60.0 [2]_, including its handling of missing cells, in which +each feature is estimated on its observed cells. Four modes, as in HarmonizR: ==== ============= =========== Mode ``par_prior`` ``mean_only`` @@ -16,39 +15,59 @@ References ---------- -.. [1] Johnson WE, Li C, Rabinovic A. "Adjusting batch effects in - microarray expression data using empirical Bayes methods." - *Biostatistics* 8(1):118-127, 2007. - -Acknowledgements ----------------- -Algorithm logic cross-referenced against: -- R ``sva::ComBat`` (Leek JT et al., Bioconductor) -- ``inmoose.pycombat`` (Behdenna A et al., GPL-3) +.. [1] Johnson WE, Li C, Rabinovic A. Adjusting batch effects in microarray + expression data using empirical Bayes methods. Biostatistics + 8(1):118-127, 2007. doi:10.1093/biostatistics/kxj037 +.. [2] Leek JT, Johnson WE, Parker HS, et al. sva: Surrogate Variable Analysis. + R package, Bioconductor. The ``inmoose`` Python port (Behdenna A et al.) + was also consulted. """ from __future__ import annotations import logging from dataclasses import dataclass -from typing import Any, cast +from typing import Any import numpy as np import numpy.typing as npt -from .validation import validate_combat_input +from .types import FloatArray +from .validation import ( + batch_codes, + reject_combat_overflow, + validate_engine_input, + validate_ref_batch, +) logger = logging.getLogger(__name__) +# Lower bound on the pooled variance and the batch scale estimates, so that a +# zero variance never divides; features below it are left raw by combat(). +_VARIANCE_FLOOR = 1e-12 + +# Size of a block of the non-parametric prior, which holds one row per target +# feature and one column per feature. A block of 2**16 cells (512 KiB) stays in +# the CPU cache, so wide groups run faster in short blocks than in tall ones. The +# block never has fewer than 16 rows, so a small group is done in one block. +# Rows are computed independently; the block size changes the output only by +# rounding in the matrix product. +_EPRIOR_BLOCK_CELLS = 2**16 +_EPRIOR_MIN_BLOCK_ROWS = 16 + # --------------------------------------------------------------------------- -# Type aliases +# Grouping records # --------------------------------------------------------------------------- -_Array = npt.NDArray[np.floating[Any]] @dataclass(frozen=True) -class _ValidRowGroups: - """Grouped row indices for a shared valid-observation mask layout.""" +class ValidRowGroups: + """Rows grouped by their pattern of observed cells. + + ``valid_masks`` marks the observed cells of every row; each entry of + ``row_groups`` holds the indices of rows with the same pattern, in order of + first appearance. + """ valid_masks: npt.NDArray[np.bool_] row_groups: tuple[npt.NDArray[np.intp], ...] @@ -56,10 +75,19 @@ class _ValidRowGroups: @dataclass(frozen=True) class _GroupedBatchDesignLayouts: - """Precomputed reduced one-hot layouts for grouped Beta.NA.""" + """Per group of rows, the one-hot design over its observed samples and their counts.""" + + reduced_designs: tuple[FloatArray | None, ...] + counts: tuple[FloatArray | None, ...] + - reduced_designs: tuple[_Array | None, ...] - counts: tuple[_Array | None, ...] +# Keyword arguments of combat() for each ComBat mode of HarmonizR and the CLI. +COMBAT_MODES: dict[int, dict[str, bool]] = { + 1: {"par_prior": True, "mean_only": False}, + 2: {"par_prior": True, "mean_only": True}, + 3: {"par_prior": False, "mean_only": False}, + 4: {"par_prior": False, "mean_only": True}, +} # --------------------------------------------------------------------------- @@ -67,22 +95,20 @@ class _GroupedBatchDesignLayouts: # --------------------------------------------------------------------------- -def _aprior(gamma_hat: _Array) -> float: - """Hyper-prior *a* for the inverse-gamma on delta (scale effect).""" - m = float(gamma_hat.mean()) - s2 = float(gamma_hat.var(ddof=1)) - if s2 <= 0.0 or np.isnan(s2): - return 1.0 # flat prior when variance cannot be estimated - return float((2.0 * s2 + m * m) / s2) - +def _hyper_priors(delta_hat: FloatArray) -> tuple[float, float]: + """Return the hyper-priors *a* and *b* of the inverse-gamma prior on one batch's scale. -def _bprior(gamma_hat: _Array) -> float: - """Hyper-prior *b* for the inverse-gamma on delta (scale effect).""" - m = float(gamma_hat.mean()) - s2 = float(gamma_hat.var(ddof=1)) + Method-of-moments estimates from the mean and variance of the batch's + scale estimates; both are 1.0 (a flat prior) when that variance is zero or + undefined. + """ + if delta_hat.size < 2: + return 1.0, 1.0 + m = float(delta_hat.mean()) + s2 = float(delta_hat.var(ddof=1)) if s2 <= 0.0 or np.isnan(s2): - return 1.0 # flat prior when variance cannot be estimated - return float((m * s2 + m**3) / s2) + return 1.0, 1.0 + return float((2.0 * s2 + m * m) / s2), float((m * s2 + m**3) / s2) # --------------------------------------------------------------------------- @@ -90,9 +116,13 @@ def _bprior(gamma_hat: _Array) -> float: # --------------------------------------------------------------------------- -def _postmean(g_bar: Any, d_star: Any, t2_n: Any, t2_n_g_hat: Any) -> _Array: - """Posterior mean of the additive batch effect (gamma).""" - return (t2_n_g_hat + d_star * g_bar) / (t2_n + d_star) # type: ignore[no-any-return] +def _postmean_unit_scale(g_bar: float, t2: float, g_hat: FloatArray) -> FloatArray: + """Posterior mean of the location effect with unit scale and n = 1. + + This is R ``sva``'s ``postmean`` as location-only mode calls it. + """ + posterior: FloatArray = (t2 * g_hat + g_bar) / (t2 + 1.0) + return posterior # --------------------------------------------------------------------------- @@ -101,123 +131,190 @@ def _postmean(g_bar: Any, d_star: Any, t2_n: Any, t2_n_g_hat: Any) -> _Array: def _it_sol( - s_data: _Array, - g_hat: _Array, - d_hat: _Array, + s_data: FloatArray, + g_hat: FloatArray, + d_hat: FloatArray, g_bar: float, t2: float, a: float, b: float, conv: float = 1e-4, max_iter: int = 1_000_000, -) -> tuple[_Array, _Array]: - """Iterative EB solver for one batch (parametric path). +) -> tuple[FloatArray, FloatArray]: + """Solve the parametric empirical-Bayes estimates for one batch. - NaN-safe: per-gene statistics are computed on non-NaN entries, - matching R sva::ComBat's handling of missing data within batches. + A one-batch call of ``_it_sol_batches``; see there for the method. Parameters ---------- - s_data : (n_genes, n_batch_samples) - Standardised data for a single batch. May contain NaN. - g_hat, d_hat : (n_genes,) - Initial estimates of additive / multiplicative effects. + s_data : ndarray, shape (n_features, n_batch_samples) + Standardised data of the batch. May contain NaN. + g_hat, d_hat : ndarray, shape (n_features,) + Location and scale estimates of the batch. g_bar, t2 : float - Prior mean and variance for gamma. + Mean and variance of the normal prior on the location. a, b : float - Hyper-priors for the inverse-gamma on delta. + Hyper-priors of the inverse-gamma prior on the scale. + conv : float + Relative change below which the iteration stops (``sva``'s 1e-4). + max_iter : int + Iteration limit; ``sva`` has none. Returns ------- - gamma_star, delta_star : (n_genes,) + gamma_star, delta_star : ndarray, shape (n_features,) """ - nan_mask = np.isnan(s_data) - all_nan = nan_mask.all(axis=1) - active = ~all_nan - - # Genes with no observed values cannot inform the EB update. Keep their - # initial estimates and skip the iterative solver entirely. - if not np.any(active): - return g_hat.copy(), d_hat.copy() - - n_per_gene = np.float64((~nan_mask).sum(axis=1)) - n_per_gene = np.maximum(n_per_gene, 1.0) - - sum_x = np.nansum(s_data, axis=1) - sum_x2 = np.nansum(s_data * s_data, axis=1) - - t2_n = t2 * n_per_gene - t2_n_g_hat = t2_n * g_hat # uses ORIGINAL g_hat, not updated g_new - - g_prev = g_hat[active].copy() - d_prev = d_hat[active].copy() - t2_n_active = t2_n[active] - t2_n_g_hat_active = t2_n_g_hat[active] - sum_x_active = sum_x[active] - sum_x2_active = sum_x2[active] - n_per_gene_active = n_per_gene[active] - d_denom = 0.5 * n_per_gene_active + a - 1.0 - - g_curr = np.empty_like(g_prev) - d_curr = np.empty_like(d_prev) - sum2 = np.empty_like(g_prev) - delta_g = np.empty_like(g_prev) - delta_d = np.empty_like(d_prev) - denom_g = np.empty_like(g_prev) - denom_d = np.empty_like(d_prev) - latest_g = g_prev - latest_d = d_prev + gamma_star, delta_star = _it_sol_batches( + s_data, + [np.arange(s_data.shape[1], dtype=np.intp)], + g_hat[np.newaxis, :], + d_hat[np.newaxis, :], + np.array([g_bar]), + np.array([t2]), + np.array([a]), + np.array([b]), + conv=conv, + max_iter=max_iter, + ) + return gamma_star[0], delta_star[0] + + +def _it_sol_batches( + s_data: FloatArray, + batches_ind: list[npt.NDArray[np.intp]], + g_hat: FloatArray, + d_hat: FloatArray, + g_bar: FloatArray, + t2: FloatArray, + a: FloatArray, + b: FloatArray, + conv: float = 1e-4, + max_iter: int = 1_000_000, +) -> tuple[FloatArray, FloatArray]: + """Solve the parametric empirical-Bayes estimates of every batch in one loop. - for iteration in range(max_iter): - np.multiply(d_prev, g_bar, out=g_curr) - g_curr += t2_n_g_hat_active - np.divide(g_curr, t2_n_active + d_prev, out=g_curr) - - np.multiply(g_curr, g_curr, out=sum2) - sum2 *= n_per_gene_active - sum2 -= 2.0 * g_curr * sum_x_active - sum2 += sum_x2_active - - d_curr[:] = 0.5 * sum2 + b - np.divide(d_curr, d_denom, out=d_curr) - - np.subtract(g_curr, g_prev, out=delta_g) - np.abs(delta_g, out=delta_g) - np.copyto(denom_g, g_prev) - np.abs(denom_g, out=denom_g) - np.maximum(denom_g, 1e-12, out=denom_g) - np.divide(delta_g, denom_g, out=delta_g) - - np.subtract(d_curr, d_prev, out=delta_d) - np.abs(delta_d, out=delta_d) - np.copyto(denom_d, d_prev) - np.abs(denom_d, out=denom_d) - np.maximum(denom_d, 1e-12, out=denom_d) - np.divide(delta_d, denom_d, out=delta_d) - - change = max(float(delta_g.max()), float(delta_d.max())) - latest_g = g_curr - latest_d = d_curr - - if change < conv: - logger.debug("Converged in %d iterations (change=%.2e)", iteration + 1, change) - break + For each batch this is R ``sva``'s ``it.sol``: alternate the posterior + location and scale of every feature until the largest relative change of + either falls below ``conv``. Each feature uses its observed cells only, and + a feature with no observed cell in a batch keeps its initial estimates. - g_prev, g_curr = g_curr, g_prev - d_prev, d_curr = d_curr, d_prev - else: - logger.warning( - "Batch did not converge after %d iterations (final change=%.2e)", - max_iter, - change, - ) + All batches iterate together, and each stops at its own convergence, so + the result equals solving the batches one at a time. The working arrays + shrink as batches converge, so a converged batch costs nothing further. + Rows of a batch are not frozen individually: as in ``sva``, every row + updates until the batch as a whole converges. Log records are written per + batch, in batch order, after the loop. - gamma_star = g_hat.copy() - delta_star = d_hat.copy() - gamma_star[active] = latest_g - delta_star[active] = latest_d + Parameters + ---------- + s_data : ndarray, shape (n_features, n_samples) + Standardised data. May contain NaN. + batches_ind : list of ndarray + Column indices of each batch. + g_hat, d_hat : ndarray, shape (n_batches, n_features) + Location and scale estimates. + g_bar, t2, a, b : ndarray, shape (n_batches,) + Prior mean and variance of the location, and hyper-priors of the scale. + conv : float + Relative change below which a batch stops (``sva``'s 1e-4). + max_iter : int + Iteration limit; a batch that reaches it is logged as not converged. - return gamma_star, delta_star + Returns + ------- + gamma_star, delta_star : ndarray, shape (n_batches, n_features) + """ + n_obs = np.empty_like(g_hat) + sum_x = np.empty_like(g_hat) + sum_x2 = np.empty_like(g_hat) + for i, idx in enumerate(batches_ind): + batch_data = s_data[:, idx] + n_obs[i] = (~np.isnan(batch_data)).sum(axis=1) + sum_x[i] = np.nansum(batch_data, axis=1) + sum_x2[i] = np.nansum(batch_data * batch_data, axis=1) + active = n_obs > 0 + n_obs = np.maximum(n_obs, 1.0) + + t2_n = t2[:, np.newaxis] * n_obs + t2_n_g_hat = t2_n * g_hat + d_denom = 0.5 * n_obs + a[:, np.newaxis] - 1.0 + + g_star = g_hat.copy() + d_star = d_hat.copy() + stop_iteration = np.zeros(len(batches_ind), dtype=np.intp) + stop_change = np.full(len(batches_ind), np.nan) + rows = np.flatnonzero(active.any(axis=1)) + g_curr, d_curr = g_hat[rows], d_hat[rows] + run_active = active[rows] + every_row_active = bool(run_active.all()) + run_t2_n, run_t2_n_g_hat, run_n_obs = t2_n[rows], t2_n_g_hat[rows], n_obs[rows] + run_sum_x, run_sum_x2, run_d_denom = sum_x[rows], sum_x2[rows], d_denom[rows] + run_g_bar, run_b = g_bar[rows, np.newaxis], b[rows, np.newaxis] + + for iteration in range(max_iter): + if rows.size == 0: + break + g_prev, d_prev = g_curr, d_curr + + g_curr = d_prev * run_g_bar + g_curr += run_t2_n_g_hat + np.divide(g_curr, run_t2_n + d_prev, out=g_curr) + + sum2 = g_curr * g_curr + sum2 *= run_n_obs + sum2 -= 2.0 * g_curr * run_sum_x + sum2 += run_sum_x2 + d_curr = 0.5 * sum2 + run_b + np.divide(d_curr, run_d_denom, out=d_curr) + + # Relative changes, guarded against a zero previous value. + delta_g = np.abs(g_curr - g_prev) / np.maximum(np.abs(g_prev), 1e-12) + delta_d = np.abs(d_curr - d_prev) / np.maximum(np.abs(d_prev), 1e-12) + if not every_row_active: + delta_g = np.where(run_active, delta_g, -np.inf) + delta_d = np.where(run_active, delta_d, -np.inf) + g_curr = np.where(run_active, g_curr, g_prev) + d_curr = np.where(run_active, d_curr, d_prev) + max_g, max_d = delta_g.max(axis=1), delta_d.max(axis=1) + # Python's max(a, b): b only when b > a, so a NaN scale change is ignored + # while the location change is finite, as in the per-batch solver. + change = np.where(max_d > max_g, max_d, max_g) + stop_change[rows] = change + + finished = ~np.isfinite(change) | (change < conv) + if not finished.any(): + continue + done = rows[finished] + stop_iteration[done] = iteration + 1 + g_star[done] = g_curr[finished] + d_star[done] = d_curr[finished] + keep = ~finished + rows = rows[keep] + g_curr, d_curr, run_active = g_curr[keep], d_curr[keep], run_active[keep] + run_t2_n, run_t2_n_g_hat, run_n_obs = run_t2_n[keep], run_t2_n_g_hat[keep], run_n_obs[keep] + run_sum_x, run_sum_x2 = run_sum_x[keep], run_sum_x2[keep] + run_d_denom, run_g_bar, run_b = run_d_denom[keep], run_g_bar[keep], run_b[keep] + + unconverged = set(rows.tolist()) + for k, row in enumerate(rows.tolist()): + g_star[row] = g_curr[k] + d_star[row] = d_curr[k] + for row in range(len(batches_ind)): + if row in unconverged: + logger.warning( + "Batch did not converge after %d iterations (final change=%.2e)", + max_iter, + stop_change[row], + ) + elif stop_iteration[row] and not np.isfinite(stop_change[row]): + logger.warning( + "Solver stopped at iteration %d: the change is not finite", stop_iteration[row] + ) + elif stop_iteration[row]: + logger.debug( + "Converged in %d iterations (change=%.2e)", stop_iteration[row], stop_change[row] + ) + return g_star, d_star # --------------------------------------------------------------------------- @@ -226,82 +323,94 @@ def _it_sol( def _int_eprior( - s_data: _Array, - g_hat: _Array, - d_hat: _Array, -) -> tuple[_Array, _Array]: - """Monte-Carlo integration for non-parametric EB estimation (one batch). - - NaN-safe: each gene uses only its non-NaN entries for the likelihood, - matching R sva::ComBat's per-gene handling where ``x <- sdat[i, !is.na(sdat[i, ])]`` - and ``n <- length(x)``. Likelihood for - gene *i* uses gene *i*'s non-NA count *n_i*, not the global batch - size. + s_data: FloatArray, + g_hat: FloatArray, + d_hat: FloatArray, +) -> tuple[FloatArray, FloatArray]: + """Non-parametric empirical-Bayes location and scale for one batch. + + Each feature's estimate is the average of the other features' estimates, + weighted by the likelihood of its observed cells under each of them + (R ``sva:::int.eprior``). The computation is deterministic: a weighted sum + over features, in blocks of target rows of at most ``_EPRIOR_BLOCK_CELLS`` + cells, or ``_EPRIOR_MIN_BLOCK_ROWS`` rows if more. + + The log-likelihood of target *i* under support *j* is written as + ``-(SS_i + n_i (m_i - g_j)^2) / (2 d_j) - n_i log(2 pi d_j) / 2``, with + *m_i* the target's mean and *SS_i* its sum of squared deviations. Expanding + the square into sums of ``x^2`` and ``x`` loses precision when a target's + values lie far from the support estimates relative to their spread, so the + deviation from the mean is formed directly, as R does. The row maximum is + subtracted before ``exp``, so the weights cannot all underflow; a row whose + weights are not finite falls back to equal weights over the other features. + The weighted sums use one matrix product per block. + + Each target uses its own observed cells and their count, as R does with + ``x <- sdat[i, !is.na(sdat[i, ])]``. Parameters ---------- - s_data : (n_genes, n_batch_samples) - g_hat, d_hat : (n_genes,) + s_data : ndarray, shape (n_features, n_batch_samples) + Standardised data of the batch; missing cells are allowed. + g_hat, d_hat : ndarray, shape (n_features,) + Location and scale estimates of the batch. Returns ------- - gamma_star, delta_star : (n_genes,) + gamma_star, delta_star : ndarray, shape (n_features,) + Posterior estimates; a feature with no observed cell keeps its input + estimates. """ - n_genes, _ = s_data.shape + n_features, _ = s_data.shape g_star = g_hat.copy() d_star = d_hat.copy() - if n_genes <= 1: + if n_features <= 1: return g_star, d_star - d = np.maximum(d_hat, 1e-12) - not_nan = ~np.isnan(s_data) - n_per_gene = not_nan.sum(axis=1).astype(np.float64) - sum_x = np.nansum(s_data, axis=1) - sum_x2 = np.nansum(s_data * s_data, axis=1) - g_hat_sq = g_hat * g_hat - log_two_pi_d = np.log(2.0 * np.pi * d) - neg_half_log_two_pi_d = -0.5 * log_two_pi_d - - block_size = 64 - for start in range(0, n_genes, block_size): - stop = min(start + block_size, n_genes) - block_indices = np.arange(start, stop, dtype=np.intp) - n_block = n_per_gene[start:stop] - valid_rows = n_block >= 1.0 - if not np.any(valid_rows): - continue - - target_indices = block_indices[valid_rows] - n_valid = n_block[valid_rows] - sum_x_valid = sum_x[start:stop][valid_rows] - sum_x2_valid = sum_x2[start:stop][valid_rows] - - log_lh = ( - sum_x2_valid[:, np.newaxis] - - 2.0 * sum_x_valid[:, np.newaxis] * g_hat[np.newaxis, :] - + n_valid[:, np.newaxis] * g_hat_sq[np.newaxis, :] - ) - np.divide(log_lh, 2.0 * d[np.newaxis, :], out=log_lh) + d = np.maximum(d_hat, _VARIANCE_FLOOR) + observed = ~np.isnan(s_data) + if observed.all(): + n_obs = np.full(n_features, float(s_data.shape[1])) + mean = s_data.sum(axis=1) / s_data.shape[1] + resid = s_data - mean[:, np.newaxis] + else: + n_obs = observed.sum(axis=1).astype(np.float64) + mean = np.nansum(s_data, axis=1) / np.maximum(n_obs, 1.0) + resid = np.where(observed, s_data - mean[:, np.newaxis], 0.0) + sum_sq = (resid * resid).sum(axis=1) + half_inv_d = 0.5 / d + half_log_two_pi_d = 0.5 * np.log(2.0 * np.pi * d) + support = np.column_stack([g_hat, d, np.ones(n_features)]) + targets = np.flatnonzero(n_obs >= 1.0) + block_rows = min( + max(targets.size, 1), max(_EPRIOR_MIN_BLOCK_ROWS, _EPRIOR_BLOCK_CELLS // n_features) + ) + buffer = np.empty((block_rows, n_features)) + + for start in range(0, targets.size, block_rows): + rows = targets[start : start + block_rows] + log_lh = buffer[: rows.size] + np.subtract(mean[rows, np.newaxis], g_hat[np.newaxis, :], out=log_lh) + np.square(log_lh, out=log_lh) + log_lh *= n_obs[rows, np.newaxis] + log_lh += sum_sq[rows, np.newaxis] + log_lh *= half_inv_d + log_lh += n_obs[rows, np.newaxis] * half_log_two_pi_d np.negative(log_lh, out=log_lh) - log_lh += n_valid[:, np.newaxis] * neg_half_log_two_pi_d[np.newaxis, :] - - row_ids = np.arange(target_indices.size, dtype=np.intp) - log_lh[row_ids, target_indices] = -np.inf - - row_max = np.max(log_lh, axis=1, keepdims=True) - log_lh -= row_max + log_lh[np.arange(rows.size), rows] = -np.inf + log_lh -= log_lh.max(axis=1, keepdims=True) np.exp(log_lh, out=log_lh) - totals = log_lh.sum(axis=1) + sums = log_lh @ support - bad_totals = (totals == 0.0) | ~np.isfinite(totals) - if np.any(bad_totals): - log_lh[bad_totals] = 1.0 - log_lh[bad_totals, target_indices[bad_totals]] = 0.0 - totals = log_lh.sum(axis=1) + bad = (sums[:, 2] == 0.0) | ~np.isfinite(sums[:, 2]) + if np.any(bad): + log_lh[bad] = 1.0 + log_lh[np.flatnonzero(bad), rows[bad]] = 0.0 + sums[bad] = log_lh[bad] @ support - g_star[target_indices] = (log_lh * g_hat[np.newaxis, :]).sum(axis=1) / totals - d_star[target_indices] = (log_lh * d[np.newaxis, :]).sum(axis=1) / totals + g_star[rows] = sums[:, 0] / sums[:, 2] + d_star[rows] = sums[:, 1] / sums[:, 2] return g_star, d_star @@ -310,43 +419,136 @@ def _int_eprior( # Design matrix # --------------------------------------------------------------------------- -_design_cache: dict[tuple[int, ...], tuple[_Array, _Array, list[npt.NDArray[np.intp]], int]] = {} +_design_cache: dict[ + tuple[int, bytes], tuple[FloatArray, FloatArray, list[npt.NDArray[np.intp]]] +] = {} +# Upper bound on the memory the design cache keeps alive between calls. +_DESIGN_CACHE_MAX_BYTES = 16 * 2**20 -def _make_design(batch: npt.NDArray[np.intp], n_batch: int) -> _Array: +def _make_design(batch: npt.NDArray[np.intp], n_batch: int) -> FloatArray: """One-hot batch design matrix, shape (n_batch, n_samples).""" n_samples = len(batch) design = np.zeros((n_batch, n_samples), dtype=np.float64) for i in range(n_batch): design[i, batch == i] = 1.0 - return design # np.float64 array satisfies _Array (NDArray[floating[Any]]) + return design def _get_cached_design( batch_int: npt.NDArray[np.intp], n_batch: int -) -> tuple[_Array, _Array, list[npt.NDArray[np.intp]], int]: - """Return cached design matrix and XXT, or compute and cache. - - When consecutive affiliation groups share the same batch layout, - this avoids recomputing the one-hot design matrix and its XXT - decomposition for every group. +) -> tuple[FloatArray, FloatArray, list[npt.NDArray[np.intp]]]: + """Return the one-hot design, its Gram matrix, and the column indices of each batch. + + Consecutive groups often share a batch layout, so results are cached by the + layout. After each insertion the oldest layouts are dropped until the cache + holds at most 64 layouts and at most ``_DESIGN_CACHE_MAX_BYTES``, so that + wide matrices do not keep large designs alive after a run; the newest + layout is always kept. """ - key = tuple(batch_int.tolist()) - if key in _design_cache: - design, xx_t, batches_ind, cached_n_batch = _design_cache[key] - if cached_n_batch == n_batch: - return design, xx_t, batches_ind, n_batch + key = (n_batch, batch_int.tobytes()) + cached = _design_cache.get(key) + if cached is not None: + return cached design = _make_design(batch_int, n_batch) - xx_t = design @ design.T - batches_ind = [np.where(batch_int == i)[0] for i in range(n_batch)] + layout = (design, design @ design.T, [np.where(batch_int == i)[0] for i in range(n_batch)]) + _design_cache[key] = layout + while len(_design_cache) > 1 and ( + len(_design_cache) > 64 or _design_cache_bytes() > _DESIGN_CACHE_MAX_BYTES + ): + del _design_cache[next(iter(_design_cache))] + return layout + + +def _design_cache_bytes() -> int: + """Return the bytes held by the design cache.""" + return sum( + entry[0].nbytes + entry[1].nbytes + sum(ind.nbytes for ind in entry[2]) + for entry in _design_cache.values() + ) + + +@dataclass(frozen=True) +class _BatchColumns: + """The columns of each batch, made contiguous by one stable sort. - # Keep cache bounded to avoid unbounded memory growth - if len(_design_cache) > 64: - _design_cache.clear() - _design_cache[key] = (design, xx_t, batches_ind, n_batch) + ``sum`` reduces each batch's columns to one column and ``expand`` repeats a + per-batch column over that batch's columns, so per-batch statistics take a + few array operations whatever the number of batches. + """ + + ids: npt.NDArray[np.intp] + sizes: npt.NDArray[np.intp] + order: npt.NDArray[np.intp] + starts: npt.NDArray[np.intp] + + @classmethod + def of(cls, batch_int: npt.NDArray[np.intp]) -> _BatchColumns: + ids, sizes = np.unique(batch_int, return_counts=True) + starts = np.concatenate(([0], np.cumsum(sizes)[:-1])).astype(np.intp) + return cls(ids, sizes, np.argsort(batch_int, kind="stable"), starts) + + def sum(self, values: npt.NDArray[Any]) -> npt.NDArray[Any]: + """Sum the columns of each batch of ``values``, whose columns are in ``order``.""" + return np.add.reduceat(values, self.starts, axis=1) + + def expand(self, per_batch: FloatArray) -> FloatArray: + """Repeat each batch's column over that batch's columns, in ``order``.""" + return np.repeat(per_batch, self.sizes, axis=1) + + +def _unestimable_rows( + data: FloatArray, + batch_int: npt.NDArray[np.intp], + *, + mean_only: bool, + ref_batch: int | None, +) -> npt.NDArray[np.bool_]: + """Return the rows whose variance the engine would replace with the floor. + + The pooled variance is computed as the engine computes it: the mean square + of the residuals from the batch means when ``data`` has no missing cell, and + their sample variance otherwise, where a row with at most one observed value + gets 1.0; with a reference batch, over that batch's columns only. A row + whose pooled variance is below ``_VARIANCE_FLOOR`` is unestimable. Outside + mean-only mode, so is a row with a batch of two or more observed values + whose variance is below ``_VARIANCE_FLOOR`` times the pooled variance, + which is the engine's batch scale estimate. Mean-only mode is in effect + when the caller asks for it or when any batch has a single sample, as in + the engines; the non-parametric modes pass ``mean_only=True`` to check the + pooled variance only. + """ + layout = _BatchColumns.of(batch_int) + mean_only = mean_only or bool(np.any(layout.sizes < 2)) + x = data[:, layout.order] + obs = ~np.isnan(x) + has_nan = not bool(obs.all()) + if has_nan: + n_obs = layout.sum(obs.astype(np.intp)) + means = layout.sum(np.where(obs, x, 0.0)) / np.maximum(n_obs, 1) + resid = np.where(obs, x - layout.expand(means), 0.0) + else: + n_obs = np.broadcast_to(layout.sizes, (x.shape[0], layout.sizes.size)) + resid = x - layout.expand(layout.sum(x) / layout.sizes) + ss = layout.sum(resid * resid) + + if ref_batch is None: + ss_pooled, n_pooled, n_cols = ss.sum(axis=1), n_obs.sum(axis=1), data.shape[1] + else: + ref = int(np.searchsorted(layout.ids, ref_batch)) + ss_pooled, n_pooled, n_cols = ss[:, ref], n_obs[:, ref], int(layout.sizes[ref]) + if has_nan: + var_pooled = np.where(n_pooled <= 1, 1.0, ss_pooled / np.maximum(n_pooled - 1, 1)) + else: + var_pooled = ss_pooled / n_cols - return design, xx_t, batches_ind, n_batch + unestimable = var_pooled < _VARIANCE_FLOOR + if not mean_only: + scale = np.maximum(var_pooled, _VARIANCE_FLOOR)[:, np.newaxis] + var_b = ss / np.maximum(n_obs - 1, 1) + unestimable |= ((n_obs >= 2) & (var_b < _VARIANCE_FLOOR * scale)).any(axis=1) + return unestimable # --------------------------------------------------------------------------- @@ -355,91 +557,238 @@ def _get_cached_design( def combat( - data: _Array, + data: FloatArray, batch: npt.ArrayLike, *, par_prior: bool = True, mean_only: bool = False, ref_batch: int | None = None, -) -> _Array: - """Apply ComBat batch-effect correction. - - Per-cell NaN is handled per-feature by omitting NaN observations from - OLS, variance, and mean computations (matching R ``sva::ComBat`` - v3.60.0's ``Beta.NA`` approach). NaN stays in the same positions in - the output. +) -> FloatArray: + """Correct batch effects with ComBat. + + Missing cells are allowed: each feature's batch means and variances use + its observed cells only, as R ``sva::ComBat`` 3.60.0 does (``Beta.NA``), + and missing cells stay missing in the output. + + Some features are returned with their raw values, and the run log counts + them: + + - A feature whose pooled within-batch variance is below the 1e-12 floor + (with ``ref_batch``, the reference batch's variance). Its values cannot + be standardised, so its correction would not be estimated from its data. + - In the parametric modes outside mean-only mode, a feature with a batch + whose variance is below 1e-12 of the pooled variance. It would otherwise + set the empirical-Bayes prior for every other feature. Location-only + mode and the non-parametric modes correct such a feature: its batch + locations are estimable, and in the non-parametric modes the floored + batch gives it no weight in the other features' priors. Its other + batches enter the shared priors, so it moves the other features as any + feature does. + - A single feature, or a single feature left after the others are set + aside, which has no other features to share a prior with. + - A feature with values in a single batch, which has no batch effect to + estimate. + - With ``ref_batch``, a feature with no value in the reference batch. + + The others are corrected as if those left raw were absent. A feature with no + observed value stays missing and does not enter the fit of the others. A feature + with no value in some batches is fitted on the batches it has: the missing batches + enter neither its grand mean nor their priors. Each batch's prior is shared, so + such a feature also enters the priors of the batches it is observed in. Parameters ---------- - data : ndarray, shape (n_features, n_samples) - Expression / abundance matrix. Per-cell NaN is allowed. - batch : ndarray, shape (n_samples,) - Integer batch labels, 0-indexed and contiguous (``0 .. n_batch-1``). + data : array_like, shape (n_features, n_samples) + Log-scale values; missing cells are allowed. Not modified. + batch : array_like, shape (n_samples,) + Batch label per sample: whole numbers, one batch per distinct value. par_prior : bool - ``True`` for parametric EB (modes 1/2). - ``False`` for non-parametric EB (modes 3/4). + Parametric empirical-Bayes priors (modes 1 and 2) when ``True``, + non-parametric (modes 3 and 4) when ``False``. mean_only : bool - ``True`` to correct location only, leave scale untouched (modes 2/4). + Correct location only and leave the scale unchanged (modes 2 and 4). + A batch with a single sample makes the fit location-only whatever this + value is. ref_batch : int or None - If given, this batch is treated as the reference and is not adjusted. + A batch left unchanged, to which the others are adjusted. It needs at + least two samples. Returns ------- ndarray, shape (n_features, n_samples) - Batch-corrected data. NaN positions from input are preserved - in the output. + The corrected values, as a new array. Raises ------ ValueError - On wrong dimensionality or batch length mismatch. + On wrong dimensionality, batch length mismatch, batch labels that are + not whole numbers, infinite values, values of magnitude 1e150 or more + (whose squares overflow the variance sums), or a ``ref_batch`` that is + not among the batch labels or has one sample. Examples -------- >>> import numpy as np >>> from harmonizepy import combat >>> data = np.random.default_rng(0).normal(10, 2, (50, 12)) - >>> batch = np.array([0]*4 + [1]*4 + [2]*4) + >>> batch = np.array([0] * 4 + [1] * 4 + [2] * 4) >>> corrected = combat(data, batch) >>> corrected.shape (50, 12) + + Notes + ----- + As in ``sva::ComBat``, the pooled variance is the mean square of the + residuals when the matrix has no missing cell and their sample variance + when it has any, so one missing cell multiplies every feature's pooled + variance by n / (n - 1), and its standard deviation by the square root of + that. The fit is logged at DEBUG level, features left raw at INFO level, + and a batch whose solver does not converge at WARNING level, on the + ``harmonizepy.combat`` logger. """ data = np.asarray(data, dtype=np.float64) - batch_int: npt.NDArray[np.intp] = np.asarray(batch, dtype=np.intp).ravel() + batch_int = batch_codes(batch) + + validate_engine_input(data, batch_int) + reject_combat_overflow(data, range(data.shape[0])) + validate_ref_batch(batch_int, ref_batch) + corrected, _ = _combat_validated( + data, batch_int, par_prior=par_prior, mean_only=mean_only, ref_batch=ref_batch + ) + return corrected + + +def _combat_with_reasons( + data: FloatArray, + batch: npt.ArrayLike, + *, + par_prior: bool = True, + mean_only: bool = False, +) -> tuple[FloatArray, npt.NDArray[np.str_]]: + """Validate and correct as ``combat()`` does, and return why each feature was left raw. - # ---- Input validation -------------------------------------------------- - validate_combat_input(data, batch_int) + The reasons are those of ``_combat_validated``; an empty string means the + feature was corrected. + """ + data = np.asarray(data, dtype=np.float64) + batch_int = batch_codes(batch) + validate_engine_input(data, batch_int) + reject_combat_overflow(data, range(data.shape[0])) + return _combat_validated( + data, batch_int, par_prior=par_prior, mean_only=mean_only, ref_batch=None + ) - n_features = data.shape[0] - # ---- Dispatch ---------------------------------------------------------- - has_nan = np.isnan(data).any() - if not has_nan: - if n_features < 2: - logger.debug("Single feature input, returning copy") - return data.copy() - return _combat_dense( - data, +def _combat_validated( + data: FloatArray, + batch_int: npt.NDArray[np.intp], + *, + par_prior: bool, + mean_only: bool, + ref_batch: int | None, +) -> tuple[FloatArray, npt.NDArray[np.str_]]: + """Set aside the features ComBat cannot fit, then run the dense or missing-value path. + + Features with no observed value stay missing. Features with values in a + single batch, features with no value in the reference batch, and features + whose variance the engine would floor keep their raw values; the + non-parametric modes check the pooled variance only. The rest are + corrected as if those features were absent. When fewer than two features + remain, they are returned as given, since a prior needs at least two. + + Returns the corrected matrix and, per feature, an empty string when it was + corrected or the reason it was not: ``"no_values"``, ``"single_batch"``, + ``"no_reference"``, ``"zero_variance"``, or ``"too_few_features"``. + """ + reasons = np.full(data.shape[0], "", dtype=" tuple[FloatArray, npt.NDArray[np.str_]]: + out = data.copy() + reasons[mask] = reason + keep = ~mask + if keep.sum() >= 2: + out[keep], reasons[keep] = _combat_validated( + data[keep], batch_int, par_prior=par_prior, mean_only=mean_only, ref_batch=ref_batch + ) + else: + reasons[keep] = "too_few_features" + return out, reasons + + no_values = np.isnan(data).all(axis=1) + if no_values.all(): + reasons[:] = "no_values" + return data.copy(), reasons + if no_values.any(): + out = data.copy() + reasons[no_values] = "no_values" + out[~no_values], reasons[~no_values] = _combat_validated( + data[~no_values], batch_int, par_prior=par_prior, mean_only=mean_only, ref_batch=ref_batch, ) + return out, reasons - # All-NaN data: return copy immediately (nothing to adjust) - if np.isnan(data).all(): - logger.debug("All-NaN input, returning copy") - return data.copy() + columns = _BatchColumns.of(batch_int) + observed_batches = (columns.sum((~np.isnan(data[:, columns.order])).astype(np.intp)) > 0).sum( + axis=1 + ) + one_batch = observed_batches < 2 + if one_batch.all(): + reasons[:] = "single_batch" + return data.copy(), reasons + if one_batch.any(): + logger.info( + "%d feature(s) with values in a single batch left uncorrected", int(one_batch.sum()) + ) + out = data.copy() + reasons[one_batch] = "single_batch" + out[~one_batch], reasons[~one_batch] = _combat_validated( + data[~one_batch], + batch_int, + par_prior=par_prior, + mean_only=mean_only, + ref_batch=ref_batch, + ) + return out, reasons - # Per-cell NaN present: use per-feature NaN-safe path (matches R - # sva::ComBat v3.60.0 Beta.NA approach). - return _combat_nan( - data, - batch_int, - par_prior=par_prior, - mean_only=mean_only, - ref_batch=ref_batch, + if ref_batch is not None: + no_reference = np.isnan(data[:, batch_int == ref_batch]).all(axis=1) + if no_reference.any(): + logger.info( + "%d feature(s) with no value in the reference batch left uncorrected", + int(no_reference.sum()), + ) + return set_aside(no_reference, "no_reference") + + unestimable = _unestimable_rows( + data, batch_int, mean_only=mean_only or not par_prior, ref_batch=ref_batch ) + if unestimable.any(): + logger.info( + "%d feature(s) with within-batch variance below the floor left uncorrected", + int(unestimable.sum()), + ) + return set_aside(unestimable, "zero_variance") + + if data.shape[0] < 2: + logger.debug("Single feature input, returning copy") + reasons[:] = "too_few_features" + return data.copy(), reasons + + missing = np.isnan(data) + if not missing.any(): + corrected = _combat_dense( + data, batch_int, par_prior=par_prior, mean_only=mean_only, ref_batch=ref_batch + ) + else: + corrected = _combat_nan( + data, batch_int, par_prior=par_prior, mean_only=mean_only, ref_batch=ref_batch + ) + return corrected, reasons # --------------------------------------------------------------------------- @@ -447,14 +796,14 @@ def combat( # --------------------------------------------------------------------------- -def _group_valid_rows(data: _Array) -> _ValidRowGroups: - """Group row indices by identical non-NaN masks.""" +def group_valid_rows(data: FloatArray) -> ValidRowGroups: + """Group row indices by their pattern of observed cells, in order of first appearance.""" valid_masks = ~np.isnan(data) packed_masks = np.packbits(valid_masks, axis=1) grouped_rows: dict[bytes, list[int]] = {} for row_index in range(data.shape[0]): grouped_rows.setdefault(packed_masks[row_index].tobytes(), []).append(row_index) - return _ValidRowGroups( + return ValidRowGroups( valid_masks=valid_masks, row_groups=tuple( np.asarray(row_indices, dtype=np.intp) for row_indices in grouped_rows.values() @@ -463,15 +812,15 @@ def _group_valid_rows(data: _Array) -> _ValidRowGroups: def _prepare_grouped_batch_design_layouts( - design: _Array, - valid_row_groups: _ValidRowGroups, + design: FloatArray, + valid_row_groups: ValidRowGroups, ) -> _GroupedBatchDesignLayouts: """Precompute reduced one-hot designs and counts for each valid-mask group.""" if valid_row_groups.valid_masks.shape[1] != design.shape[1]: raise ValueError("valid_row_groups width does not match design") - reduced_designs: list[_Array | None] = [] - counts: list[_Array | None] = [] + reduced_designs: list[FloatArray | None] = [] + counts: list[FloatArray | None] = [] for row_indexer in valid_row_groups.row_groups: valid = valid_row_groups.valid_masks[row_indexer[0]] if not valid.any(): @@ -490,17 +839,17 @@ def _prepare_grouped_batch_design_layouts( def _beta_na_grouped_batch_design( - data: _Array, - design: _Array, - valid_row_groups: _ValidRowGroups, + data: FloatArray, + design: FloatArray, + valid_row_groups: ValidRowGroups, grouped_design_layouts: _GroupedBatchDesignLayouts | None = None, -) -> _Array: - """Grouped Beta.NA specialized for the one-hot batch design. +) -> FloatArray: + """Return each feature's batch means over its observed cells (sva's ``Beta.NA``). - `_combat_nan()` always uses the cached one-hot batch design from - `_make_design()`. For that design, the least-squares coefficient for each - batch is just the mean over the observed samples in that batch, with the - minimum-norm solution `0` for batches with no observed values. + With the one-hot batch design, the least-squares coefficient of a batch is + the mean of the feature's observed values in it; a batch with no observed + value gets 0, the minimum-norm solution. Rows with the same pattern of + observed cells are computed together. Shape (n_batches, n_features). """ n_features, _ = data.shape betas = np.empty((design.shape[0], n_features), dtype=np.float64) @@ -538,19 +887,18 @@ def _beta_na_grouped_batch_design( def _row_var_nan_grouped( - data: _Array, - valid_row_groups: _ValidRowGroups | None = None, -) -> _Array: - """Row-wise sample variance grouped by identical valid-observation masks. - - For a fixed validity mask, rows share the same reduced submatrix. - Compute `ddof=1` variances on that reduced view in one batched pass - while preserving the existing 0/1-valid-entry handling. + data: FloatArray, + valid_row_groups: ValidRowGroups | None = None, +) -> FloatArray: + """Return each row's sample variance (``ddof=1``) over its observed cells. + + Rows with the same pattern of observed cells are computed together. A row + with at most one observed cell gets 1.0. """ n_features, _ = data.shape variances = np.empty(n_features, dtype=np.float64) - groups = valid_row_groups or _group_valid_rows(data) + groups = valid_row_groups or group_valid_rows(data) if groups.valid_masks.shape != data.shape: raise ValueError("valid_row_groups shape does not match data") @@ -575,296 +923,271 @@ def _row_var_nan_grouped( # --------------------------------------------------------------------------- -def _combat_nan( - data: _Array, - batch_int: npt.NDArray[np.intp], - *, - par_prior: bool = True, - mean_only: bool = False, - ref_batch: int | None = None, -) -> _Array: - """ComBat correction with per-feature NaN handling. - - For each feature independently, NaN observations are omitted from OLS, - variance, and mean computations. NaN positions are preserved in the - output. This matches R sva::ComBat v3.60.0's ``Beta.NA`` approach. +@dataclass(frozen=True) +class _BatchLayout: + """Batches of one ComBat fit, relabelled 0 to n_batch - 1.""" + + batch_idx: npt.NDArray[np.intp] + n_batch: int + ref_idx: int | None + design: FloatArray + xx_t: FloatArray + batches_ind: list[npt.NDArray[np.intp]] + batch_sizes: FloatArray + mean_only: bool + + +def _batch_layout( + batch_int: npt.NDArray[np.intp], ref_batch: int | None, *, mean_only: bool +) -> _BatchLayout: + """Relabel the batches, build the design, and settle location-only mode. + + Location-only mode is used when the caller asks for it or when any batch + has a single sample, which has no variance of its own. """ - n_features, n_samples = data.shape - - unique_batches = np.unique(batch_int) - n_batch = len(unique_batches) - if n_batch < 2: - logger.debug("Single batch input, returning copy") - return data.copy() - - logger.info( - "ComBat (NaN-safe) %s, %s: %d features x %d samples across %d batches", - "parametric" if par_prior else "non-parametric", - "location+scale" if not mean_only else "location only", - n_features, - n_samples, - n_batch, - ) - - # Remap batch labels to 0..n_batch-1 - label_map = {old: new for new, old in enumerate(unique_batches)} - batch_int = np.array([label_map[b] for b in batch_int], dtype=np.intp) - if ref_batch is not None: - if ref_batch not in label_map: - raise ValueError( - f"ref_batch={ref_batch!r} not found in batch labels {sorted(label_map.keys())}" - ) - ref_idx = label_map[ref_batch] - else: - ref_idx = None - - design, _, batches_ind, _ = _get_cached_design(batch_int, n_batch) + labels, batch_idx = np.unique(batch_int, return_inverse=True) + batch_idx = batch_idx.astype(np.intp) + n_batch = len(labels) + ref_idx = None if ref_batch is None else int(np.flatnonzero(labels == ref_batch)[0]) + if ref_idx is not None: + logger.debug("Reference batch: original %s -> remapped %d", ref_batch, ref_idx) + design, xx_t, batches_ind = _get_cached_design(batch_idx, n_batch) batch_sizes = np.array([len(b) for b in batches_ind], dtype=np.float64) - if not mean_only and np.any(batch_sizes < 2): logger.debug("Forcing mean_only=True: batch with < 2 samples detected") mean_only = True - - valid_row_groups = _group_valid_rows(data) - grouped_design_layouts = _prepare_grouped_batch_design_layouts(design, valid_row_groups) - - # ---- Per-feature B.hat (Beta.NA) --------------------------------------- - b_hat = _beta_na_grouped_batch_design( - data, - design, - valid_row_groups, - grouped_design_layouts, + return _BatchLayout( + batch_idx, n_batch, ref_idx, design, xx_t, batches_ind, batch_sizes, mean_only ) - # ---- Grand mean and pooled variance (per-feature, NaN-safe) ------------ - # NOTE: R sva::ComBat uses DIFFERENT formulas: - # No NaN: mean(residuals^2) - # Has NaN: rowVars(residuals, na.rm=TRUE) (sample variance, ddof=1) - if ref_idx is not None: - grand_mean = b_hat[ref_idx] - ref_cols = batches_ind[ref_idx] - fitted_ref = (design[:, ref_cols].T @ b_hat).T - var_n = _row_var_nan_grouped(data[:, ref_cols] - fitted_ref) - else: - grand_mean = (batch_sizes / n_samples) @ b_hat - fitted = (design.T @ b_hat).T - var_n = _row_var_nan_grouped(data - fitted, valid_row_groups) - - var_pooled = np.maximum(var_n, 1e-12) - std_pooled = np.sqrt(var_pooled) - stand_mean = grand_mean[:, np.newaxis] - std_pooled_2d = std_pooled[:, np.newaxis] - - # ---- Standardise (per-feature, NaN-safe) ------------------------------- - s_data = (data - stand_mean) / std_pooled_2d - # ---- Per-feature gamma.hat (Beta.NA) ----------------------------------- - gamma_hat = _beta_na_grouped_batch_design( - s_data, - design, - valid_row_groups, - grouped_design_layouts, - ) - - # ---- delta.hat (per-batch, per-feature, NaN-safe) ---------------------- - if mean_only: - delta_hat = np.ones_like(gamma_hat) +def _estimate_batch_effects( + s_data: FloatArray, + gamma_hat: FloatArray, + delta_hat: FloatArray, + layout: _BatchLayout, + *, + par_prior: bool, + observed: npt.NDArray[np.bool_] | None = None, +) -> tuple[FloatArray, FloatArray]: + """Shrink the per-batch location and scale estimates with the empirical-Bayes prior. + + Parametric modes use the normal and inverse-gamma priors (the iterative + solver, or the closed-form posterior mean in location-only mode); + non-parametric modes use the likelihood-weighted average over features. + The reference batch, if any, gets location 0 and scale 1. + + *observed*, shape (n_batches, n_features), marks the batches in which each + feature has a value; ``None`` means every feature has a value in every + batch. A batch's prior then uses only the features observed in it; the + estimates of a feature for a batch it lacks have no cell to adjust. A batch + observed by fewer than two features has no prior to estimate, so its + location and scale estimates are used unshrunk. + """ + few: npt.NDArray[np.bool_] | None = None + if observed is None: + gamma_bar = gamma_hat.mean(axis=1) + t2 = gamma_hat.var(axis=1, ddof=1) + delta_for_prior = list(delta_hat) else: - delta_hat = np.empty_like(gamma_hat) - for b in range(n_batch): - idx = batches_ind[b] - delta_hat[b] = _row_var_nan_grouped(s_data[:, idx]) - - # ---- EB prior (same as dense path) ------------------------------------ - gamma_bar = gamma_hat.mean(axis=1) - t2 = gamma_hat.var(axis=1, ddof=1) - - if par_prior and not mean_only: - a_prior = np.array([_aprior(delta_hat[i]) for i in range(n_batch)]) - b_prior = np.array([_bprior(delta_hat[i]) for i in range(n_batch)]) + few = observed.sum(axis=1) < 2 + # Placeholder priors keep the shrinkage finite for batches whose + # estimates are restored unshrunk below. + gamma_bar = np.array( + [0.0 if few[i] else gamma_hat[i, observed[i]].mean() for i in range(layout.n_batch)] + ) + t2 = np.array( + [ + 1.0 if few[i] else gamma_hat[i, observed[i]].var(ddof=1) + for i in range(layout.n_batch) + ] + ) + delta_for_prior = [delta_hat[i, observed[i]] for i in range(layout.n_batch)] + if par_prior and not layout.mean_only: + priors = [_hyper_priors(delta_for_prior[i]) for i in range(layout.n_batch)] else: - a_prior = np.ones(n_batch) - b_prior = np.ones(n_batch) - - # ---- Solve for batch effects (NaN-safe solvers) ----------------------- - gamma_star = np.empty_like(gamma_hat) - delta_star = np.empty_like(gamma_hat) + priors = [(1.0, 1.0)] * layout.n_batch - for i, idx in enumerate(batches_ind): - batch_s_data = s_data[:, idx] - if par_prior: - if mean_only: - # R's postmean gets n=1 for mean_only mode - t2_n = t2[i] * 1.0 - t2_n_g_hat = t2_n * gamma_hat[i] - gamma_star[i] = _postmean(gamma_bar[i], 1.0, t2_n, t2_n_g_hat) + if par_prior and not layout.mean_only: + a_prior = np.array([prior[0] for prior in priors]) + b_prior = np.array([prior[1] for prior in priors]) + gamma_star, delta_star = _it_sol_batches( + s_data, layout.batches_ind, gamma_hat, delta_hat, gamma_bar, t2, a_prior, b_prior + ) + else: + gamma_star = np.empty_like(gamma_hat) + delta_star = np.empty_like(gamma_hat) + for i, idx in enumerate(layout.batches_ind): + if par_prior: + gamma_star[i] = _postmean_unit_scale(gamma_bar[i], t2[i], gamma_hat[i]) delta_star[i] = 1.0 + elif observed is None: + gamma_star[i], d_star = _int_eprior(s_data[:, idx], gamma_hat[i], delta_hat[i]) + delta_star[i] = 1.0 if layout.mean_only else d_star else: - gamma_star[i], delta_star[i] = _it_sol( - batch_s_data, - gamma_hat[i], - delta_hat[i], - gamma_bar[i], - t2[i], - a_prior[i], - b_prior[i], + rows = observed[i] + gamma_star[i], delta_star[i] = gamma_hat[i], delta_hat[i] + g_sub, d_sub = _int_eprior( + s_data[rows][:, idx], gamma_hat[i, rows], delta_hat[i, rows] ) - else: - d_hat_i = np.ones_like(delta_hat[i]) if mean_only else delta_hat[i] - g_s, d_s = _int_eprior(batch_s_data, gamma_hat[i], d_hat_i) - gamma_star[i] = g_s - delta_star[i] = d_s if not mean_only else np.ones_like(g_s) - - if ref_idx is not None: - gamma_star[ref_idx] = 0.0 - delta_star[ref_idx] = 1.0 - - # ---- Adjust data (only non-NaN entries) ------------------------------- - corrected = s_data.copy() - for i, idx in enumerate(batches_ind): - sqrt_delta = np.sqrt(np.maximum(delta_star[i], 1e-12))[:, np.newaxis] - corrected[:, idx] = (corrected[:, idx] - gamma_star[i][:, np.newaxis]) / sqrt_delta + gamma_star[i, rows] = g_sub + delta_star[i, rows] = 1.0 if layout.mean_only else d_sub + + if few is not None and few.any(): + gamma_star[few] = gamma_hat[few] + delta_star[few] = 1.0 if layout.mean_only else delta_hat[few] + if layout.ref_idx is not None: + gamma_star[layout.ref_idx] = 0.0 + delta_star[layout.ref_idx] = 1.0 + return gamma_star, delta_star - corrected = corrected * std_pooled_2d + stand_mean - if ref_idx is not None: - corrected[:, batches_ind[ref_idx]] = data[:, batches_ind[ref_idx]] +def _adjust( + s_data: FloatArray, + data: FloatArray, + gamma_star: FloatArray, + delta_star: FloatArray, + std_pooled: FloatArray, + stand_mean: FloatArray, + layout: _BatchLayout, +) -> FloatArray: + """Remove the batch effects from the standardised data and return to the data scale. - return cast(_Array, corrected) + ``s_data`` is overwritten. Reference-batch columns are returned as given. + """ + for i, idx in enumerate(layout.batches_ind): + sqrt_delta = np.sqrt(np.maximum(delta_star[i], _VARIANCE_FLOOR))[:, np.newaxis] + s_data[:, idx] = (s_data[:, idx] - gamma_star[i][:, np.newaxis]) / sqrt_delta + s_data *= std_pooled[:, np.newaxis] + s_data += stand_mean + if layout.ref_idx is not None: + ref_cols = layout.batches_ind[layout.ref_idx] + s_data[:, ref_cols] = data[:, ref_cols] + return s_data + + +def _log_fit(data: FloatArray, layout: _BatchLayout, *, par_prior: bool, label: str) -> None: + logger.debug( + "%s %s, %s: %d features x %d samples across %d batches", + label, + "parametric" if par_prior else "non-parametric", + "location+scale" if not layout.mean_only else "location only", + data.shape[0], + data.shape[1], + layout.n_batch, + ) -def _combat_dense( - data: _Array, +def _combat_nan( + data: FloatArray, batch_int: npt.NDArray[np.intp], *, par_prior: bool = True, mean_only: bool = False, ref_batch: int | None = None, -) -> _Array: - """Dense (NaN-free) ComBat correction. See ``combat()`` for docs.""" - n_features, n_samples = data.shape - - unique_batches = np.unique(batch_int) - n_batch = len(unique_batches) - if n_batch < 2: +) -> FloatArray: + """ComBat correction with per-feature handling of missing cells. + + Each feature's batch means and variances use its observed cells only + (R ``sva::ComBat`` 3.60.0's ``Beta.NA``). The pooled variance is the sample + variance of the residuals (``rowVars(..., na.rm = TRUE)`` in sva), not the + mean square the dense path uses; sva switches formula the same way. + Missing cells stay missing. + """ + if len(np.unique(batch_int)) < 2: logger.debug("Single batch input, returning copy") return data.copy() - - mod_label = "parametric" if par_prior else "non-parametric" - scale_label = "location+scale" if not mean_only else "location only" - logger.info( - "ComBat %s, %s: %d features x %d samples across %d batches", - mod_label, - scale_label, - n_features, - n_samples, - n_batch, - ) - - # Remap batch labels to 0..n_batch-1 - label_map = {old: new for new, old in enumerate(unique_batches)} - batch_int = np.array([label_map[b] for b in batch_int], dtype=np.intp) - - if ref_batch is not None: - if ref_batch not in label_map: - raise ValueError( - f"ref_batch={ref_batch!r} not found in batch labels {sorted(label_map.keys())}" - ) - ref_idx = label_map[ref_batch] - logger.debug("Reference batch: original %s -> remapped %d", ref_batch, ref_idx) + layout = _batch_layout(batch_int, ref_batch, mean_only=mean_only) + _log_fit(data, layout, par_prior=par_prior, label="ComBat (NaN-safe)") + + valid_row_groups = group_valid_rows(data) + grouped_layouts = _prepare_grouped_batch_design_layouts(layout.design, valid_row_groups) + b_hat = _beta_na_grouped_batch_design(data, layout.design, valid_row_groups, grouped_layouts) + observed = np.stack([(~np.isnan(data[:, idx])).any(axis=1) for idx in layout.batches_ind]) + partial = ~observed.all(axis=0) + + if layout.ref_idx is not None: + grand_mean = b_hat[layout.ref_idx] + ref_cols = layout.batches_ind[layout.ref_idx] + fitted_ref = (layout.design[:, ref_cols].T @ b_hat).T + var_n = _row_var_nan_grouped(data[:, ref_cols] - fitted_ref) else: - ref_idx = None + grand_mean = (layout.batch_sizes / data.shape[1]) @ b_hat + if partial.any(): + weights = observed[:, partial] * layout.batch_sizes[:, np.newaxis] + grand_mean[partial] = (weights * b_hat[:, partial]).sum(axis=0) / weights.sum(axis=0) + residuals = (layout.design.T @ b_hat).T + np.subtract(data, residuals, out=residuals) + var_n = _row_var_nan_grouped(residuals, valid_row_groups) + del residuals + + std_pooled = np.sqrt(np.maximum(var_n, _VARIANCE_FLOOR)) + stand_mean = grand_mean[:, np.newaxis] + s_data = data - stand_mean + s_data /= std_pooled[:, np.newaxis] - design, xx_t, batches_ind, _ = _get_cached_design(batch_int, n_batch) - batch_sizes = np.array([len(b) for b in batches_ind], dtype=np.float64) + gamma_hat = _beta_na_grouped_batch_design( + s_data, layout.design, valid_row_groups, grouped_layouts + ) + delta_hat = np.ones_like(gamma_hat) + if not layout.mean_only: + for b, idx in enumerate(layout.batches_ind): + delta_hat[b] = _row_var_nan_grouped(s_data[:, idx]) - if not mean_only and np.any(batch_sizes < 2): - logger.debug("Forcing mean_only=True: batch with < 2 samples detected") - mean_only = True + gamma_star, delta_star = _estimate_batch_effects( + s_data, + gamma_hat, + delta_hat, + layout, + par_prior=par_prior, + observed=observed if partial.any() else None, + ) + return _adjust(s_data, data, gamma_star, delta_star, std_pooled, stand_mean, layout) - # ---- Standardise ------------------------------------------------------- - B_hat = np.linalg.solve(xx_t, design @ data.T) # noqa: N806 - if ref_idx is not None: - grand_mean = B_hat[ref_idx] - else: - grand_mean = (batch_sizes / n_samples) @ B_hat +def _combat_dense( + data: FloatArray, + batch_int: npt.NDArray[np.intp], + *, + par_prior: bool = True, + mean_only: bool = False, + ref_batch: int | None = None, +) -> FloatArray: + """ComBat correction of a matrix without missing cells. - if ref_idx is not None: - ref_cols = batches_ind[ref_idx] - fitted = design[:, ref_cols].T @ B_hat - residuals = data[:, ref_cols].T - fitted - var_pooled = (residuals**2).mean(axis=0) + The pooled variance is the mean square of the residuals from the batch + means, as in R ``sva::ComBat`` for complete data. See ``combat()``. + """ + if len(np.unique(batch_int)) < 2: + logger.debug("Single batch input, returning copy") + return data.copy() + layout = _batch_layout(batch_int, ref_batch, mean_only=mean_only) + _log_fit(data, layout, par_prior=par_prior, label="ComBat") + + b_hat = np.linalg.solve(layout.xx_t, layout.design @ data.T) + if layout.ref_idx is not None: + grand_mean = b_hat[layout.ref_idx] + ref_cols = layout.batches_ind[layout.ref_idx] + residuals = data[:, ref_cols].T - layout.design[:, ref_cols].T @ b_hat else: - fitted = design.T @ B_hat - residuals = data.T - fitted - var_pooled = (residuals**2).mean(axis=0) + grand_mean = (layout.batch_sizes / data.shape[1]) @ b_hat + residuals = data.T - layout.design.T @ b_hat + np.square(residuals, out=residuals) + var_pooled = residuals.mean(axis=0) + del residuals - var_pooled = np.maximum(var_pooled, 1e-12) - std_pooled = np.sqrt(var_pooled) + std_pooled = np.sqrt(np.maximum(var_pooled, _VARIANCE_FLOOR)) stand_mean = grand_mean[:, np.newaxis] - s_data = (data - stand_mean) / std_pooled[:, np.newaxis] + s_data = data - stand_mean + s_data /= std_pooled[:, np.newaxis] - # ---- Estimate batch effects -------------------------------------------- - gamma_hat = np.linalg.solve(xx_t, design @ s_data.T) - - if mean_only: - delta_hat = np.ones_like(gamma_hat) - else: - delta_hat = np.empty_like(gamma_hat) - for i, idx in enumerate(batches_ind): + gamma_hat = np.linalg.solve(layout.xx_t, layout.design @ s_data.T) + delta_hat = np.ones_like(gamma_hat) + if not layout.mean_only: + for i, idx in enumerate(layout.batches_ind): delta_hat[i] = s_data[:, idx].var(axis=1, ddof=1) - gamma_bar = gamma_hat.mean(axis=1) - t2 = gamma_hat.var(axis=1, ddof=1) - - if par_prior and not mean_only: - a_prior = np.array([_aprior(delta_hat[i]) for i in range(n_batch)]) - b_prior = np.array([_bprior(delta_hat[i]) for i in range(n_batch)]) - else: - a_prior = np.ones(n_batch) - b_prior = np.ones(n_batch) - - gamma_star = np.empty_like(gamma_hat) - delta_star = np.empty_like(gamma_hat) - - for i, idx in enumerate(batches_ind): - batch_s_data = s_data[:, idx] - if par_prior: - if mean_only: - t2_n = t2[i] * 1.0 - t2_n_g_hat = t2_n * gamma_hat[i] - gamma_star[i] = _postmean(gamma_bar[i], 1.0, t2_n, t2_n_g_hat) - delta_star[i] = 1.0 - else: - gamma_star[i], delta_star[i] = _it_sol( - batch_s_data, - gamma_hat[i], - delta_hat[i], - gamma_bar[i], - t2[i], - a_prior[i], - b_prior[i], - ) - else: - d_hat_i = np.ones_like(delta_hat[i]) if mean_only else delta_hat[i] - g_star_i, d_star_i = _int_eprior(batch_s_data, gamma_hat[i], d_hat_i) - gamma_star[i] = g_star_i - delta_star[i] = d_star_i if not mean_only else 1.0 - - if ref_idx is not None: - gamma_star[ref_idx] = 0.0 - delta_star[ref_idx] = 1.0 - - # ---- Adjust data ------------------------------------------------------- - corrected = s_data.copy() - for i, idx in enumerate(batches_ind): - sqrt_delta = np.sqrt(np.maximum(delta_star[i], 1e-12))[:, np.newaxis] - corrected[:, idx] = (corrected[:, idx] - gamma_star[i][:, np.newaxis]) / sqrt_delta - - corrected = corrected * std_pooled[:, np.newaxis] + stand_mean - - if ref_idx is not None: - corrected[:, batches_ind[ref_idx]] = data[:, batches_ind[ref_idx]] - - return corrected # type: ignore[no-any-return] + gamma_star, delta_star = _estimate_batch_effects( + s_data, gamma_hat, delta_hat, layout, par_prior=par_prior + ) + return _adjust(s_data, data, gamma_star, delta_star, std_pooled, stand_mean, layout) diff --git a/src/harmonizepy/combat_wrapper.py b/src/harmonizepy/combat_wrapper.py index 8f5b22c..16388dc 100644 --- a/src/harmonizepy/combat_wrapper.py +++ b/src/harmonizepy/combat_wrapper.py @@ -1,42 +1,34 @@ -"""ComBat integration layer. - -Thin public API that maps HarmonizR-style integer modes (1-4) to the -underlying ``harmonizepy.combat.combat`` parameters. -""" +"""ComBat on a DataFrame, with HarmonizR's integer modes 1 to 4.""" from __future__ import annotations import logging import numpy as np +import numpy.typing as npt import pandas as pd -from .combat import combat +from .combat import COMBAT_MODES, combat +from .validation import batch_codes, validate_combat_mode logger = logging.getLogger(__name__) -_MODE_MAP: dict[int, dict[str, bool]] = { - 1: {"par_prior": True, "mean_only": False}, - 2: {"par_prior": True, "mean_only": True}, - 3: {"par_prior": False, "mean_only": False}, - 4: {"par_prior": False, "mean_only": True}, -} - def adjust_combat( sub_df: pd.DataFrame, - batch_labels: np.ndarray, + batch_labels: npt.ArrayLike, mode: int = 1, ref_batch: int | None = None, ) -> pd.DataFrame: - """Apply ComBat batch correction to a complete sub-matrix. + """Correct a features x samples DataFrame with ComBat in one of modes 1 to 4. Parameters ---------- sub_df : pd.DataFrame - Features x samples. **Must have no missing values.** + Features x samples. Missing cells are allowed and stay missing. batch_labels : array-like - Integer batch label per sample (length == ``sub_df.shape[1]``). + Batch label per sample, whole numbers (length ``sub_df.shape[1]``). + With a single batch, a copy of *sub_df* is returned. mode : {1, 2, 3, 4} 1 = parametric, location + scale (default). 2 = parametric, location only. @@ -54,7 +46,8 @@ def adjust_combat( Raises ------ ValueError - If *sub_df* contains NaN, has < 2 rows, or *mode* is invalid. + If *mode* is not 1 to 4, the batch labels are not whole numbers or do + not match the number of columns, or ``combat()`` rejects the input. Examples -------- @@ -64,13 +57,14 @@ def adjust_combat( ... "s3": [5.0, 6.0], "s4": [7.0, 8.0]}) >>> corrected = adjust_combat(df, [0, 0, 1, 1], mode=2) """ - if mode not in _MODE_MAP: + validate_combat_mode(mode) + + batch_labels = batch_codes(batch_labels) + if batch_labels.shape[0] != sub_df.shape[1]: raise ValueError( - f"combat_mode must be 1, 2, 3, or 4, got {mode}. " - f"Modes 1/2 are parametric; 3/4 are non-parametric." + f"batch length ({batch_labels.shape[0]}) does not match the number of " + f"sample columns in data ({sub_df.shape[1]})." ) - - batch_labels = np.asarray(batch_labels, dtype=np.intp).ravel() if len(np.unique(batch_labels)) < 2: logger.debug( "Single batch in sub-matrix (%d x %d), passing through", @@ -89,7 +83,7 @@ def adjust_combat( sub_df.to_numpy(dtype=np.float64), batch_labels, ref_batch=ref_batch, - **_MODE_MAP[mode], + **COMBAT_MODES[mode], ) return pd.DataFrame(corrected, index=sub_df.index, columns=sub_df.columns) diff --git a/src/harmonizepy/core.py b/src/harmonizepy/core.py index df46422..ac164a2 100644 --- a/src/harmonizepy/core.py +++ b/src/harmonizepy/core.py @@ -1,19 +1,25 @@ -"""Core pipeline entry point for HarmonizePy. +"""The ``harmonize()`` pipeline and the steps it shares with the command line. -Orchestrates the full batch-correction workflow: +A run reads and validates the inputs, maps samples to batches, optionally +sorts the batches and groups neighbouring batches into blocks, finds each +feature's affiliation (the blocks in which it has enough values), applies +unique removal, corrects each group of features that share an affiliation +with ComBat or limma, and reassembles the matrix in the input column order:: - read → [sort] → [block] → spot missing → [unique removal] - → split → adjust (ComBat / limma) → concat → [re-sort] → write + read -> validate -> [sort] -> [block] -> affiliation -> [unique removal] + -> correct each group -> reassemble -> [write] -This mirrors the R ``HarmonizR::harmonizR()`` function. +The pipeline follows R ``HarmonizR::harmonizR()`` from HarmonizR 1.10.0. The +differences are listed in ``assets/FEATURE_PARITY.md``. """ from __future__ import annotations import logging import time +from dataclasses import dataclass from pathlib import Path -from typing import Literal +from typing import Literal, overload import numpy as np import numpy.typing as npt @@ -21,15 +27,23 @@ from .affiliation import build_affiliation_list, remove_unique_combinations from .blocking import build_block_list -from .io import read_description, read_main_data, write_output +from .io import _read_data_matrix, clean_features, read_description, write_output from .sorting import sort_batches -from .splitting import splitting -from .types import HarmonizeConfig -from .validation import validate_data_matrix, validate_description, validate_harmonize_args +from .splitting import _correct_groups +from .types import HarmonizeConfig, HarmonizeResult +from .validation import ( + check_input_scale, + reject_combat_overflow, + sample_batch_map, + validate_data_matrix, + validate_description, + validate_harmonize_args, +) logger = logging.getLogger(__name__) +@overload def harmonize( data: pd.DataFrame | str | Path, description: pd.DataFrame | str | Path, @@ -42,72 +56,153 @@ def harmonize( block: int | None = None, unique_removal: bool = True, output_file: str | Path | None = None, -) -> pd.DataFrame: - """Run the full HarmonizePy batch-correction pipeline. + return_report: Literal[False] = False, +) -> pd.DataFrame: ... + + +@overload +def harmonize( + data: pd.DataFrame | str | Path, + description: pd.DataFrame | str | Path, + *, + config: HarmonizeConfig | None = None, + algorithm: Literal["ComBat", "limma"] = "ComBat", + combat_mode: int = 1, + needed_values: int | None = None, + sort: str | None = None, + block: int | None = None, + unique_removal: bool = True, + output_file: str | Path | None = None, + return_report: Literal[True], +) -> HarmonizeResult: ... + + +@overload +def harmonize( + data: pd.DataFrame | str | Path, + description: pd.DataFrame | str | Path, + *, + config: HarmonizeConfig | None = None, + algorithm: Literal["ComBat", "limma"] = "ComBat", + combat_mode: int = 1, + needed_values: int | None = None, + sort: str | None = None, + block: int | None = None, + unique_removal: bool = True, + output_file: str | Path | None = None, + return_report: bool = ..., +) -> pd.DataFrame | HarmonizeResult: ... + + +def harmonize( + data: pd.DataFrame | str | Path, + description: pd.DataFrame | str | Path, + *, + config: HarmonizeConfig | None = None, + algorithm: Literal["ComBat", "limma"] = "ComBat", + combat_mode: int = 1, + needed_values: int | None = None, + sort: str | None = None, + block: int | None = None, + unique_removal: bool = True, + output_file: str | Path | None = None, + return_report: bool = False, +) -> pd.DataFrame | HarmonizeResult: + """Correct batch effects in a matrix with missing values. Parameters ---------- data : DataFrame, str, or Path - Features x samples matrix (may contain NaN for structural - missingness). If a path, read from that TSV file. + Features x samples matrix, feature names as the index. Missing cells + are allowed and stay missing. A path is read as ``read_main_data`` + reads it: ``.csv`` as comma-separated, ``.parquet`` or ``.pq`` as Parquet, and + anything else as tab-separated. description : DataFrame, str, or Path - Batch description with columns ``ID``, ``sample``, ``batch``. - If a path, read from that CSV file. + Batch description, one row per sample. The columns named ``ID`` and + ``batch`` hold the sample names and batch labels; without those + names, the first and third columns are used. Batch labels must be + whole numbers. A path is read as CSV. config : HarmonizeConfig or None - If provided, all algorithm settings are taken from this object. - Individual keyword arguments (``algorithm``, ``combat_mode``, - ``needed_values``, ``sort``, ``block``, ``unique_removal``) are - ignored when *config* is given. Useful for re-running or - storing reproducible run configurations. - algorithm : ``"ComBat"`` or ``"limma"`` - Adjustment algorithm. - combat_mode : int - ComBat mode 1-4 (ignored when *algorithm* is ``"limma"``). + Settings for the run. When given, it replaces ``algorithm``, + ``combat_mode``, ``needed_values``, ``sort``, ``block``, and + ``unique_removal``. + algorithm : {"ComBat", "limma"} + Correction engine. + combat_mode : {1, 2, 3, 4} + ComBat mode: 1 parametric location and scale, 2 parametric location + only, 3 non-parametric location and scale, 4 non-parametric location + only. Has no effect with limma, but must still be one of the four. needed_values : int or None - Minimum non-missing values per batch for a feature to enter - a sub-matrix. ``None`` (default) auto-selects: 2 for modes - 1, 3 and limma; 1 for modes 2, 4. - sort : ``"sparsity"``, ``"jaccard"``, ``"seriation"``, or ``None`` - Batch sorting strategy. Reorders batch columns so similar - batches become adjacent before blocking. Has no effect on - output when *block* is ``None``; allowed without *block* to - match R behaviour. + Minimum observed values a feature needs in a batch for that batch to + count in its affiliation; with ``block``, a block counts only when + every batch in it has that many. ``None`` chooses 2 for limma and + modes 1 and 3, and 1 for modes 2 and 4. + sort : {"sparsity", "jaccard", "seriation"} or None + Batch order used to form blocks. It changes the output only together + with ``block``. block : int or None - Block size: number of consecutive (optionally sorted) batches - to group into one block during dissection. Must be >= 2 and - strictly less than the total number of unique batches. - ``None`` (default) disables blocking. + Number of neighbouring batches per block, at least 2 and fewer than + the number of batches. ``None`` treats every batch as its own block. unique_removal : bool - When ``True`` (default), singleton features (those whose - batch-presence pattern is unique across all features) are - rescued by cropping to the nearest shared pattern before - splitting. Mirrors R's ``ur=TRUE`` default. + When ``True``, a feature whose affiliation no other feature shares is + moved to the longest affiliation of another feature that lies within + its own and spans at least two batches, as R ``ur = TRUE`` does, and + its values in the dropped blocks become missing; see + ``remove_unique_combinations``. output_file : str, Path, or None - If given, write the corrected matrix to this TSV path. + If given, the corrected matrix is also written here, in the format of + the suffix (``.csv``, ``.parquet`` or ``.pq``, otherwise TSV). + return_report : bool + When ``True``, return the corrected matrix together with a report of + what happened to each feature: its status, the batches of its group, + the group size, whether unique removal cropped it, and how many of its + repeats were removed. Returns ------- - DataFrame - Batch-corrected matrix (features x samples), in the original - column order. NaN values remain where the feature lacked - sufficient data in a batch. + DataFrame or HarmonizeResult + Corrected matrix with the input's features and columns, in the input + order, except that a feature repeated with the same name and values + appears once. A feature's values in batches outside its affiliation + are missing; a feature with no usable batch is all missing. A feature + alone in its affiliation, one whose affiliation spans a single batch, + with ComBat one whose variance is too small to estimate or whose group + has too few estimable features left, and with limma one with no more + values than batches in its group keep their raw values; the report + status names each kind (see ``correction_report``). With + ``return_report=True``, a ``HarmonizeResult`` of the matrix and the + report. Raises ------ ValueError - On invalid arguments, mismatched inputs, or duplicate features. + On an invalid argument, a matrix or description that fails + validation, or a feature name repeated with different values. + TypeError + If ``unique_removal`` is not a bool. + OSError + If a path cannot be read or ``output_file`` cannot be written. + ImportError + If a Parquet file is read or written without ``pyarrow``. + + Warns + ----- + InputScaleWarning + When the values do not look log-transformed; see ``check_input_scale``. Examples -------- - >>> from harmonizepy import harmonize - >>> result = harmonize("data.tsv", "batch.csv") - >>> result = harmonize(df, desc_df, algorithm="limma") - >>> result = harmonize(df, desc_df, combat_mode=3, needed_values=1) - >>> result = harmonize(df, desc_df, sort="sparsity", block=2) - >>> cfg = HarmonizeConfig(algorithm="limma", sort_strategy="sparsity", block_size=2) - >>> result = harmonize(df, desc_df, config=cfg) + >>> from harmonizepy import HarmonizeConfig, harmonize + >>> result = harmonize("data.tsv", "batch.csv") # doctest: +SKIP + >>> result = harmonize(df, desc, algorithm="limma") # doctest: +SKIP + >>> cfg = HarmonizeConfig(sort_strategy="sparsity", block_size=2) + >>> result = harmonize(df, desc, config=cfg) # doctest: +SKIP + + Notes + ----- + The inputs are not modified. Progress is logged at INFO level on the + ``harmonizepy`` loggers. """ - # --- Apply config (overrides individual kwargs when provided) ---------- if config is not None: algorithm = config.algorithm combat_mode = config.combat_mode @@ -116,153 +211,327 @@ def harmonize( block = config.block_size unique_removal = config.unique_removal - # --- Determine needed_values (before validation) ------------------------ - if needed_values is None: - if algorithm == "limma" or combat_mode in (1, 3): - needed_values = 2 - else: - needed_values = 1 + start_time = time.monotonic() + inputs = prepare_inputs( + data, + description, + algorithm=algorithm, + combat_mode=combat_mode, + needed_values=needed_values, + sort=sort, + block=block, + unique_removal=unique_removal, + ) + plan = plan_affiliations( + inputs.data, + inputs.batch_list, + sort=sort, + block=block, + needed_values=inputs.needed_values, + unique_removal=unique_removal, + ) + + logger.info("Adjusting %d unique affiliation group(s)", plan.n_groups) + result, reasons, group_sizes = _correct_groups( + plan.affiliation_list, + plan.data, + plan.batch_list, + plan.block_list, + algorithm=algorithm, + combat_mode=combat_mode, + output_col_order=plan.col_order, + output_columns=inputs.data.columns if plan.col_order is not None else None, + data_np=plan.data_np, + ) + + n_features = inputs.data.shape[0] + if plan.n_empty == n_features: + logger.warning( + "All %d features dropped: no feature meets needed_values=%d " + "in any batch. Output is all-NaN.", + n_features, + inputs.needed_values, + ) + + if output_file is not None: + logger.info("Writing output to %s", output_file) + write_output(result, str(output_file)) + + logger.info("Done (%.2fs).", time.monotonic() - start_time) + if not return_report: + return result + return HarmonizeResult(result, correction_report(inputs, plan, reasons, group_sizes)) + - _start_time = time.monotonic() +def resolve_needed_values(algorithm: str, combat_mode: int, needed_values: int | None) -> int: + """Return the minimum observations per batch, choosing the default when it is ``None``. - # --- Validate basic arguments (before data load) ---------------------- + The default is 2 for limma and the location-and-scale ComBat modes (1 and 3), + which estimate a variance per batch, and 1 for the location-only modes (2 + and 4). + """ + if needed_values is not None: + return needed_values + return 2 if algorithm == "limma" or combat_mode in (1, 3) else 1 + + +@dataclass(frozen=True) +class PreparedInputs: + """Validated inputs of a run: the cleaned matrix and its batch labels.""" + + data: pd.DataFrame + batch_list: npt.NDArray[np.int64] + needed_values: int + n_batches: int + repeats_removed: pd.Series + + +def prepare_inputs( + data: pd.DataFrame | str | Path, + description: pd.DataFrame | str | Path, + *, + algorithm: str, + combat_mode: int, + needed_values: int | None, + sort: str | None, + block: int | None, + unique_removal: bool, +) -> PreparedInputs: + """Read, clean, and validate the inputs of a run, and map samples to batches. + + Shared by ``harmonize()`` and the command line dry run, so that both apply + the same checks. Paths are read as ``read_main_data`` and + ``read_description`` read them; repeated features are counted, then removed + by ``clean_features``. + + Parameters + ---------- + data, description + As in ``harmonize()``. + algorithm, combat_mode, needed_values, sort, block, unique_removal + As in ``harmonize()``; ``needed_values`` may be ``None``. + + Returns + ------- + PreparedInputs + The cleaned matrix, the batch label of each of its columns, the + resolved ``needed_values``, and the number of batches. + + Raises + ------ + ValueError, TypeError + From the argument, matrix, and description checks in ``validation``. + OSError, ImportError + From reading a path: a missing or unreadable file, or Parquet without + ``pyarrow``. + """ + resolved = resolve_needed_values(algorithm, combat_mode, needed_values) validate_harmonize_args( - algorithm, - combat_mode, - needed_values, - sort_strategy=sort, - unique_removal=unique_removal, + algorithm, combat_mode, resolved, sort_strategy=sort, unique_removal=unique_removal ) - - # --- Read inputs ------------------------------------------------------- if isinstance(data, (str, Path)): logger.debug("Reading data from %s", data) - data = read_main_data(str(data)) - assert isinstance(data, pd.DataFrame) # narrow: always DataFrame after load - + data = _read_data_matrix(str(data)) if isinstance(description, (str, Path)): logger.debug("Reading description from %s", description) description = read_description(str(description)) - assert isinstance(description, pd.DataFrame) # narrow: always DataFrame after load - # --- Validate inputs --------------------------------------------------- + repeated = data.index.duplicated(keep="first") + repeats_removed = pd.Series(data.index[repeated]).value_counts(dropna=False) + data = clean_features(data) validate_data_matrix(data) validate_description(description, data) - - n_features, n_samples = data.shape - logger.info( - "Input: %d features x %d samples", - n_features, - n_samples, - ) - - # --- Extract batch labels aligned to data column order ----------------- - # Look up ID and batch columns by name (robust to column reordering), - # falling back to positional indexing for backwards compatibility. - if "ID" in description.columns and "batch" in description.columns: - id_col = description["ID"] - batch_col = description["batch"] - else: - id_col = description.iloc[:, 0] - batch_col = description.iloc[:, 2] - sample_to_batch = dict(zip(id_col.astype(str), batch_col.astype(int), strict=True)) - batch_list = np.array([sample_to_batch[col] for col in data.columns], dtype=np.int64) - - # --- Validate block_size now that we know n_batches -------------------- + values = data.to_numpy(dtype=np.float64) + check_input_scale(values) + if algorithm == "ComBat": + reject_combat_overflow(values, data.index) + logger.info("Input: %d features x %d samples", data.shape[0], data.shape[1]) + + sample_to_batch = sample_batch_map(description) + batch_list = np.array([sample_to_batch[str(col)] for col in data.columns], dtype=np.int64) n_batches = len(np.unique(batch_list)) - validate_harmonize_args( - algorithm, - combat_mode, - needed_values, - block_size=block, - n_batches=n_batches, - ) - + validate_harmonize_args(algorithm, combat_mode, resolved, block_size=block, n_batches=n_batches) logger.info( "Algorithm: %s%s | batches: %d | needed_values: %d", algorithm, f" mode {combat_mode}" if algorithm == "ComBat" else "", n_batches, - needed_values, + resolved, ) + return PreparedInputs(data, batch_list, resolved, n_batches, repeats_removed) - # --- Sort batches ------------------------------------------------------ + +@dataclass(frozen=True) +class AffiliationPlan: + """The groups a run corrects, after sorting, blocking, and unique removal.""" + + data: pd.DataFrame + data_np: npt.NDArray[np.float64] + batch_list: npt.NDArray[np.integer] + block_list: npt.NDArray[np.integer] + col_order: npt.NDArray[np.intp] | None + affiliation_list: list[tuple[int, ...]] + n_empty: int + cropped: npt.NDArray[np.bool_] + + @property + def n_groups(self) -> int: + """Number of distinct non-empty affiliations, one sub-matrix each.""" + return len({a for a in self.affiliation_list if a}) + + +def plan_affiliations( + data: pd.DataFrame, + batch_list: npt.NDArray[np.int64], + *, + sort: str | None, + block: int | None, + needed_values: int, + unique_removal: bool, +) -> AffiliationPlan: + """Sort batches, build blocks, find each feature's affiliation, and apply unique removal. + + Shared by ``harmonize()`` and the command line dry run, so that the dry run + reports the groups the correction uses. + + Parameters + ---------- + data : DataFrame + Cleaned features x samples matrix. + batch_list : ndarray of int64, shape (n_samples,) + Batch label of each column of *data*. + sort, block, needed_values, unique_removal + As in ``harmonize()``, with ``needed_values`` resolved. + + Returns + ------- + AffiliationPlan + The matrix and labels in sorted column order, the block of each + column, the permutation back to the input order (``None`` without + sorting), and each feature's affiliation. + """ + n_features = data.shape[0] + n_batches = len(np.unique(batch_list)) col_order: npt.NDArray[np.intp] | None = None - original_columns = data.columns + sorted_batches: npt.NDArray[np.integer] = batch_list if sort is not None: logger.info("Sorting %d batches by '%s'", n_batches, sort) - data, batch_list, col_order = sort_batches( # type: ignore[assignment] + data, sorted_batches, col_order = sort_batches( data, batch_list, strategy=sort, needed_values=needed_values ) - # --- Build block list -------------------------------------------------- if block is not None: - logger.info("Blocking: %d batches → blocks of size %d", n_batches, block) - block_list = build_block_list(batch_list, block_size=block) + logger.info("Blocking: %d batches in blocks of %d", n_batches, block) + block_list = build_block_list(sorted_batches, block_size=block) else: - block_list = batch_list + block_list = sorted_batches data_np = data.to_numpy(dtype=np.float64) - - # --- Spot missing values ----------------------------------------------- affiliation_list = build_affiliation_list( - data, - batch_list, - block_list, - needed_values, - data_np=data_np, + data, sorted_batches, block_list, needed_values, data_np=data_np ) - n_empty = sum(1 for a in affiliation_list if len(a) == 0) + n_empty = sum(1 for a in affiliation_list if not a) logger.debug( - "Spotting: %d features with data, %d features dropped (insufficient observations)", + "Spotting: %d features with data, %d features without a usable batch", n_features - n_empty, n_empty, ) - # --- Unique removal ---------------------------------------------------- + cropped = np.zeros(n_features, dtype=np.bool_) if unique_removal: - before_ur = sum(1 for a in affiliation_list if len(a) == 0) - affiliation_list = remove_unique_combinations(affiliation_list) - after_ur = sum(1 for a in affiliation_list if len(a) == 0) - rescued = before_ur - after_ur - if rescued > 0: + batches_per_block = { + int(blk): int(np.unique(sorted_batches[block_list == blk]).size) + for blk in np.unique(block_list) + } + new_list = remove_unique_combinations(affiliation_list, batches_per_block) + cropped = np.array( + [old != new for old, new in zip(affiliation_list, new_list, strict=True)], + dtype=np.bool_, + ) + n_cropped = int(cropped.sum()) + affiliation_list = new_list + if n_cropped: logger.info( - "Unique removal rescued %d feature(s) (%.1f%%)", - rescued, - 100.0 * rescued / n_features, + "Unique removal moved %d feature(s) into a shared pattern (%.1f%%)", + n_cropped, + 100.0 * n_cropped / n_features, ) else: - logger.debug("Unique removal: no singleton patterns found") + logger.debug("Unique removal: no feature had a pattern of its own") - # --- Split, adjust, rebuild -------------------------------------------- - n_groups = len({a for a in affiliation_list if len(a) > 0}) - logger.info("Adjusting %d unique affiliation group(s)…", n_groups) - result = splitting( - affiliation_list, - data, - batch_list, - block_list, - algorithm=algorithm, - combat_mode=combat_mode, - output_col_order=col_order, - output_columns=original_columns if col_order is not None else None, - data_np=data_np, + return AffiliationPlan( + data, data_np, sorted_batches, block_list, col_order, affiliation_list, n_empty, cropped ) - # --- Warn if all features were dropped -------------------------------- - if n_empty == n_features: - logger.warning( - "All %d features dropped: no feature meets needed_values=%d " - "in any batch. Output is all-NaN.", - n_features, - needed_values, - ) - - # --- Write output ------------------------------------------------------ - if output_file is not None: - logger.info("Writing output to %s", output_file) - write_output(result, str(output_file)) - _elapsed = time.monotonic() - _start_time - logger.info("Done (%.2fs).", _elapsed) - return result +# Report status for each reason ``_correct_groups`` gives for leaving a feature raw. +# ComBat's ``no_values`` cannot occur in a group, whose features all have values; +# it maps to the status of a feature with no usable batch, which is all missing too. +_STATUS_BY_REASON = { + "": "corrected", + "no_usable_batch": "missing_no_usable_batch", + "no_values": "missing_no_usable_batch", + "single_batch": "raw_single_batch", + "alone_in_pattern": "raw_alone_in_pattern", + "zero_variance": "raw_zero_variance", + "too_few_features": "raw_too_few_features", + "too_few_values": "raw_too_few_values", +} + + +def correction_report( + inputs: PreparedInputs, + plan: AffiliationPlan, + reasons: npt.NDArray[np.str_], + group_sizes: npt.NDArray[np.intp], +) -> pd.DataFrame: + """Build the per-feature report of a run. + + One row per feature of the corrected matrix, in its order, indexed by + feature name, with the columns: + + - ``status``: ``corrected``; ``raw_single_batch`` (its group spans one + batch); ``raw_alone_in_pattern`` (no other feature shares its + affiliation); ``raw_zero_variance`` (ComBat: variance too small to + estimate); ``raw_too_few_features`` (ComBat: fewer than two + features left in its group to form a prior); ``raw_too_few_values`` + (limma: no more values than batches, so the fit leaves no residual); + or + ``missing_no_usable_batch`` (no batch, or with ``block`` no block, with + enough values; the row is all missing). + - ``batches_used``: the batch labels of the feature's group, + comma-separated and sorted; empty when the feature was not corrected. + - ``group_size``: the number of features in its group, 0 for none. + - ``cropped``: whether unique removal moved it to a smaller affiliation, + so that the values in the dropped batches are missing in the output. + - ``repeats_removed``: how many repeated rows with its name and values + were removed before correction. + """ + batches_of_block: dict[int, set[int]] = {} + for block_id, batch_id in zip(plan.block_list.tolist(), plan.batch_list.tolist(), strict=True): + batches_of_block.setdefault(int(block_id), set()).add(int(batch_id)) + labels_of_affiliation: dict[tuple[int, ...], str] = {} + batches_used = [] + for affiliation, reason in zip(plan.affiliation_list, reasons.tolist(), strict=True): + if reason: + batches_used.append("") + continue + label = labels_of_affiliation.get(affiliation) + if label is None: + batches = sorted(set().union(*(batches_of_block[b] for b in affiliation))) + label = ",".join(str(b) for b in batches) + labels_of_affiliation[affiliation] = label + batches_used.append(label) + + index = inputs.data.index + report = pd.DataFrame( + { + "status": [_STATUS_BY_REASON[r] for r in reasons.tolist()], + "batches_used": batches_used, + "group_size": group_sizes, + "cropped": plan.cropped, + "repeats_removed": inputs.repeats_removed.reindex(index, fill_value=0).to_numpy(), + }, + index=index, + ) + return report diff --git a/src/harmonizepy/io.py b/src/harmonizepy/io.py index 5a5ae47..7249d16 100644 --- a/src/harmonizepy/io.py +++ b/src/harmonizepy/io.py @@ -1,13 +1,23 @@ -"""Input and output helpers. +"""Reading and writing the data matrix and the batch description. -Read/write HarmonizR-compatible data and batch description files. +The data matrix is read from tab- or comma-separated text with pandas' C +parser, or from Parquet with pyarrow, with the first column as feature names, +as R ``read.table(header = TRUE, row.names = 1)`` reads HarmonizR's input. +Repeated features are resolved by ``clean_features``. Outputs are written as +TSV, CSV, or Parquet by suffix. """ from __future__ import annotations +import csv import logging +import secrets +from collections import Counter +from collections.abc import Callable from pathlib import Path +from typing import Any +import numpy as np import pandas as pd logger = logging.getLogger(__name__) @@ -18,56 +28,218 @@ except ImportError: _HAVE_PYARROW = False -# CSV/TSV reading: pyarrow engine is faster for tall/narrow data but slower -# for very wide data (thousands of columns). We sample the header line to -# count columns and pick the engine accordingly. -_WIDE_COLUMN_THRESHOLD = 500 +def _header_fields(path: str, sep: str) -> list[str]: + """Return the fields of the header line of a delimited file, quotes removed.""" + with Path(path).open(encoding="utf-8", newline="") as fh: + return next(csv.reader(fh, delimiter=sep), []) -def _count_columns(path: str, sep: str) -> int: - """Return the number of columns in the header line of a delimited file. - Reads a single line from the file (header), splits by *sep*, and - returns the length. Cost is microseconds for any reasonable file. - """ - with Path(path).open() as fh: - header = fh.readline() - return len(header.split(sep)) +def _reject_repeated_sample_names(path: str, sep: str) -> None: + """Raise ``ValueError`` if a sample name appears twice in the header. + The parsers rename a repeated header (``s1`` becomes ``s1.1``), so the check + reads the header itself. The first field names the feature column. + """ + counts = Counter(_header_fields(path, sep)[1:]) + repeated = sorted(name for name, count in counts.items() if count > 1) + if repeated: + raise ValueError( + f"data contains duplicate sample names: {repeated[:5]}. " + "Each column must have a unique name." + ) -def _use_pyarrow_csv(path: str, sep: str) -> bool: - """Return ``True`` if pyarrow engine should be used for this CSV/TSV file. - PyArrow is preferred for files with ``<= _WIDE_COLUMN_THRESHOLD`` columns - (where it is typically faster) and slower for very wide files. +# Output format for each file suffix; any other suffix writes TSV. +_FORMAT_BY_SUFFIX: dict[str, str] = { + ".tsv": "tsv", + ".txt": "tsv", + ".csv": "csv", + ".parquet": "parquet", + ".pq": "parquet", +} + + +def format_from_suffix(path: str) -> str: + """Return ``"tsv"``, ``"csv"``, or ``"parquet"`` from the suffix of *path*; TSV otherwise.""" + return _FORMAT_BY_SUFFIX.get(Path(path).suffix.lower(), "tsv") + + +# pandas' default missing-value markers. They are applied to every column +# except the one that holds names, so that a feature called ``NA`` or a sample +# called ``null`` keeps its name. +_MISSING_MARKERS: tuple[str, ...] = ( + "", + "#N/A", + "#N/A N/A", + "#NA", + "-1.#IND", + "-1.#QNAN", + "-NaN", + "-nan", + "1.#IND", + "1.#QNAN", + "", + "N/A", + "NA", + "NULL", + "NaN", + "None", + "n/a", + "nan", + "null", +) + + +def _read_delimited(path: str, sep: str, *, name_col: int, index_col: int | None) -> pd.DataFrame: + """Read a delimited file with pandas' C parser, keeping column *name_col* as text. + + The name column is read as written: no type inference (``01`` stays + ``01``) and no missing-value markers (``NA`` stays ``NA``). The other + columns read blanks and pandas' default markers as missing. + + The C parser runs on the calling thread. pyarrow's CSV reader is not used: + it starts a thread pool, and on this package's inputs it is no faster on + narrow files and slower on wide ones. """ - return bool(_HAVE_PYARROW and _count_columns(path, sep) <= _WIDE_COLUMN_THRESHOLD) + n_cols = len(_header_fields(path, sep)) + # Keys are column positions; pandas accepts them, though its stubs name str keys. + markers: dict[Any, list[str]] = { + i: list(_MISSING_MARKERS) for i in range(n_cols) if i != name_col + } + return pd.read_csv( + path, + sep=sep, + index_col=index_col, + engine="c", + dtype={name_col: str}, + keep_default_na=False, + na_values=markers, + ) + +def _to_numpy_dtypes(df: pd.DataFrame) -> pd.DataFrame: + """Convert extension-typed columns and index, as Parquet produces, to NumPy dtypes. -def _convert_pyarrow_dtypes(df: pd.DataFrame) -> pd.DataFrame: - """Convert pyarrow-backed columns and index to standard numpy dtypes in-place.""" + The frame is changed in place and returned. A column of blanks becomes + float64; an integer column with a missing cell becomes float64 with NaN, + since NumPy integers cannot hold a missing value, and without one it stays + int64; other columns become float64 or text. Text files and Parquet files + with the same content then give the same dtypes. + """ if not _HAVE_PYARROW: return df from pandas import ArrowDtype - # Columns - pa_cols = [col for col in df.columns if isinstance(df[col].dtype, ArrowDtype)] - for col in pa_cols: + ext_cols = [col for col in df.columns if pd.api.types.is_extension_array_dtype(df[col].dtype)] + for col in ext_cols: dtype = df[col].dtype - if pd.api.types.is_integer_dtype(dtype): - df[col] = df[col].astype(int) + if df[col].isna().all(): + df[col] = df[col].astype(float) + elif pd.api.types.is_integer_dtype(dtype): + df[col] = df[col].astype(float if df[col].isna().any() else int) elif pd.api.types.is_float_dtype(dtype): df[col] = df[col].astype(float) else: df[col] = df[col].astype(str) - # Index if isinstance(df.index.dtype, ArrowDtype): df.index = df.index.astype(str) return df +def _names_for_log(names: list[str]) -> str: + """Return up to ten names for a log line.""" + shown = ", ".join(names[:10]) + return shown + (", ..." if len(names) > 10 else "") + + +def clean_features(df: pd.DataFrame) -> pd.DataFrame: + """Remove repeated features. + + A feature is a repeat when its name and all of its values match an earlier + row, with missing cells in the same places; the repeat is removed and logged + at INFO level. Features with different names are kept even when their values + are identical. A name that appears more than once with different values + raises ``ValueError``. + + The rows that share a name are checked in one pass: each is compared with + the first row of its name, missing cells equal to missing cells. For + frames that are not all numeric, exact repeats of name and values are + dropped and any name left twice has two value sets. + + The input frame is not changed; when no name repeats, it is returned as is. + + Parameters + ---------- + df : DataFrame + Features x samples matrix, with feature names as the index. + + Returns + ------- + DataFrame + The matrix without the removed rows, in the original order. + + Raises + ------ + ValueError + If a feature name appears more than once with different values. + """ + has_repeated_name = df.index.duplicated(keep=False) + if not has_repeated_name.any(): + return df + + shared = df[has_repeated_name] + codes, _ = pd.factorize(shared.index, use_na_sentinel=False) + if all(pd.api.types.is_numeric_dtype(dtype) for dtype in shared.dtypes): + values = shared.to_numpy(dtype=np.float64) + _, first_row = np.unique(codes, return_index=True) + reference = values[first_row[codes]] + same = (values == reference) | (np.isnan(values) & np.isnan(reference)) + differs = ~same.all(axis=1) + else: + # Columns renamed to positions so the code column, -1, cannot collide + # with a sample name. + keyed = shared.set_axis(range(shared.shape[1]), axis=1) + keyed[-1] = codes + distinct = keyed.drop_duplicates() + conflict_codes = distinct[-1][distinct[-1].duplicated()] + differs = np.isin(codes, conflict_codes.to_numpy()) + if differs.any(): + name = shared.index[np.flatnonzero(differs)[0]] + raise ValueError( + f"duplicate feature names with different values: {str(name)!r} appears more " + "than once. Each feature name must have one set of values." + ) + + is_repeat = df.index.duplicated(keep="first") + removed_names = [str(n) for n in pd.unique(df.index[is_repeat])] + logger.info( + "Removed %d repeated feature(s) with identical values: %s", + int(is_repeat.sum()), + _names_for_log(removed_names), + ) + return df.loc[~is_repeat] + + +def _read_data_matrix(path: str) -> pd.DataFrame: + """Read a data matrix file as ``read_main_data`` does, without removing repeats.""" + ext = Path(path).suffix.lower() + if ext in (".parquet", ".pq"): + if not _HAVE_PYARROW: + raise ImportError("Parquet reading requires pyarrow: pip install harmonizepy[io]") + df = pd.read_parquet(path, engine="pyarrow", use_threads=False) + else: + sep = "," if ext == ".csv" else "\t" + _reject_repeated_sample_names(path, sep) + df = _read_delimited(path, sep, name_col=0, index_col=0) + df = _to_numpy_dtypes(df) + if df.index.name == "": + df.index.name = None + return df + + def read_main_data(path: str) -> pd.DataFrame: """Read a features x samples data matrix. @@ -79,7 +251,11 @@ def read_main_data(path: str) -> pd.DataFrame: The file must have a header row and use the first column as row names (feature identifiers), matching R - ``read.table(sep="\\t", header=TRUE, row.names=1)``. + ``read.table(sep="\\t", header=TRUE, row.names=1)``. Blank cells and pandas' + default missing-value markers (among them ``NA``, ``NaN``, ``nan``, + ``null``, ``N/A``, ``#N/A``, ``None``, ````) are read as missing in + the sample columns. Feature names are read as written, as text: a feature + named ``NA`` keeps that name, and ``001`` stays ``001``. An empty index name is set to ``None``. Parameters ---------- @@ -89,7 +265,9 @@ def read_main_data(path: str) -> pd.DataFrame: Returns ------- DataFrame - Numeric matrix with feature names as index and sample names as columns. + Matrix with feature names as index and sample names as columns, one + row per input row except removed repeats (see ``clean_features``). + Rows with no value are kept. Raises ------ @@ -97,6 +275,10 @@ def read_main_data(path: str) -> pd.DataFrame: If *path* does not exist. ImportError If *path* is parquet and ``pyarrow`` is not installed. + ValueError + If a sample name appears twice in the header of a delimited file, or + a feature name appears more than once with different values. A + feature repeated with identical values is removed and logged. Examples -------- @@ -105,42 +287,7 @@ def read_main_data(path: str) -> pd.DataFrame: >>> df = read_main_data("data.csv") # doctest: +SKIP >>> df = read_main_data("data.parquet") # doctest: +SKIP """ - ext = Path(path).suffix.lower() - - if ext in (".parquet", ".pq"): - if not _HAVE_PYARROW: - raise ImportError("Parquet reading requires pyarrow: pip install harmonizepy[io]") - df = pd.read_parquet(path, engine="auto") - elif ext == ".csv": - if _HAVE_PYARROW and _count_columns(path, ",") <= _WIDE_COLUMN_THRESHOLD: - df = pd.read_csv(path, sep=",", index_col=0, engine="pyarrow", dtype_backend="pyarrow") - else: - df = pd.read_csv(path, sep=",", index_col=0) - else: - if _HAVE_PYARROW and _count_columns(path, "\t") <= _WIDE_COLUMN_THRESHOLD: - df = pd.read_csv(path, sep="\t", index_col=0, engine="pyarrow", dtype_backend="pyarrow") - else: - df = pd.read_csv(path, sep="\t", index_col=0) - - df = _convert_pyarrow_dtypes(df) - - df = df.dropna(how="all", axis=0) - - # Remove duplicate rows (matching R HarmonizR behavior) - n_before = df.shape[0] - df = df.drop_duplicates() - if df.shape[0] < n_before: - logger.debug( - "Removed %d duplicate feature(s) from input; %d remain", - n_before - df.shape[0], - df.shape[0], - ) - - # Normalise index name: pyarrow engine may set it to empty string - # where the default C parser leaves it as None. - if df.index.name == "": - df.index.name = None - + df = clean_features(_read_data_matrix(path)) logger.debug( "Read data matrix: %d features x %d samples from %s", df.shape[0], @@ -156,14 +303,18 @@ def read_description(path: str) -> pd.DataFrame: Parameters ---------- path : str - Path to the comma-separated file. Expected columns: ``ID`` - (sample name), ``sample`` (integer index), ``batch`` (integer - batch label). + Path to the comma-separated file, with at least three columns; the ID + column is read as written, as text, so ``01`` stays ``01``: + ``ID`` (sample name), ``sample`` (not read), and ``batch`` (whole-number + batch label). Without the names ``ID`` and ``batch``, the first + column holds the sample IDs and the third the batch labels. Returns ------- DataFrame - Batch description with columns ID, sample, batch. + The file's columns as read, one row per sample, with a default + integer index. ``harmonize()`` checks them with + ``validate_description``; this function does not. Raises ------ @@ -175,11 +326,9 @@ def read_description(path: str) -> pd.DataFrame: >>> from harmonizepy.io import read_description >>> desc = read_description("batch.csv") # doctest: +SKIP """ - if _use_pyarrow_csv(path, ","): - desc = pd.read_csv(path, engine="pyarrow", dtype_backend="pyarrow") - else: - desc = pd.read_csv(path) - desc = _convert_pyarrow_dtypes(desc) + header = _header_fields(path, ",") + id_col = header.index("ID") if "ID" in header else 0 + desc = _to_numpy_dtypes(_read_delimited(path, ",", name_col=id_col, index_col=None)) logger.debug( "Read description: %d samples, %d columns from %s", desc.shape[0], desc.shape[1], path @@ -215,16 +364,62 @@ def write_output(df: pd.DataFrame, path: str) -> None: >>> import pandas as pd >>> from harmonizepy.io import write_output >>> df = pd.DataFrame({"s1": [1.0, 2.0]}, index=["f1", "f2"]) - >>> write_output(df, "/tmp/out.tsv") # doctest: +SKIP + >>> write_output(df, "corrected.tsv") # doctest: +SKIP """ - ext = Path(path).suffix.lower() - if ext in (".parquet", ".pq"): + write_frame(df, path, format_from_suffix(path)) + + logger.debug("Wrote output: %d features x %d samples to %s", df.shape[0], df.shape[1], path) + + +def write_frame(df: pd.DataFrame, path: str, fmt: str) -> None: + """Write *df* to *path* as ``"tsv"``, ``"csv"``, or ``"parquet"``, with the index. + + The file is written through ``write_atomically``, so a failed write leaves + no partial file at *path* and keeps any file that was there. + + Raises + ------ + ImportError + If *fmt* is ``"parquet"`` and ``pyarrow`` is not installed. + OSError + If *path* is not writable. + """ + if fmt == "parquet": if not _HAVE_PYARROW: raise ImportError("Parquet output requires pyarrow: pip install harmonizepy[io]") - df.to_parquet(path, index=True, engine="pyarrow") - elif ext == ".csv": - df.to_csv(path) + write_atomically(path, lambda tmp: df.to_parquet(tmp, index=True, engine="pyarrow")) + elif fmt == "csv": + write_atomically(path, lambda tmp: df.to_csv(tmp)) else: - df.to_csv(path, sep="\t") + write_atomically(path, lambda tmp: df.to_csv(tmp, sep="\t")) - logger.debug("Wrote output: %d features x %d samples to %s", df.shape[0], df.shape[1], path) + +def write_atomically(path: str, write: Callable[[str], object]) -> None: + """Call *write* on a temporary file beside *path*, then rename it to *path*. + + The temporary file is in the target's directory, so the rename is atomic + on one file system, and it is created with an ordinary open, so it gets + the permissions the user's umask gives any new file. When *write* fails, + the temporary file is removed, the error is raised again, and a file that + already existed at *path* is unchanged. + + Raises + ------ + OSError + If the directory of *path* does not exist or is not writable, or the + rename fails. + """ + target = Path(path) + tmp = target.with_name(f".{target.name}.{secrets.token_hex(6)}.tmp") + try: + with tmp.open("xb"): + pass + except OSError as error: + # Name the path the user gave, not the hidden temporary file. + raise type(error)(error.errno, error.strerror, str(target)) from error + try: + write(str(tmp)) + tmp.replace(target) + except BaseException: + tmp.unlink(missing_ok=True) + raise diff --git a/src/harmonizepy/limma_wrapper.py b/src/harmonizepy/limma_wrapper.py index af3aaf4..eb98bef 100644 --- a/src/harmonizepy/limma_wrapper.py +++ b/src/harmonizepy/limma_wrapper.py @@ -1,77 +1,85 @@ -"""limma-style batch correction (removeBatchEffect), pure NumPy. - -Reimplements the algorithm from R limma::removeBatchEffect: - -1. Encode batch as sum-to-zero contrasts (``contr.sum``). -2. Build design ``[intercept | batch_contrasts]``. -3. OLS fit: ``beta = (X'X)^{-1} X' Y'``. -4. Subtract batch component: ``Y - beta_batch @ X_batch'``. - -Reference ---------- -Ritchie ME et al. "limma powers differential expression analyses for -RNA-sequencing and microarray studies." *Nucleic Acids Research* -43(7):e47, 2015. +"""Batch correction by a linear model, as R ``limma::removeBatchEffect`` does. + +Batch is encoded as sum-to-zero contrasts (R's ``contr.sum``), the design is +an intercept plus those contrasts, each feature is fitted by least squares, +and the fitted batch component is subtracted. Features that share a pattern +of observed cells are fitted together. + +References +---------- +Ritchie ME et al. limma powers differential expression analyses for +RNA-sequencing and microarray studies. Nucleic Acids Research 43(7):e47, +2015. doi:10.1093/nar/gkv007 """ from __future__ import annotations import logging -from typing import Any import numpy as np import numpy.typing as npt import pandas as pd -from .validation import validate_limma_input +from .combat import group_valid_rows +from .types import FloatArray +from .validation import batch_codes, validate_engine_input logger = logging.getLogger(__name__) -_Array = npt.NDArray[np.floating[Any]] +def _contrast_design(batch: npt.NDArray[np.intp]) -> tuple[FloatArray, FloatArray]: + """Return the intercept-plus-batch design and its batch columns, with sum-to-zero contrasts. -def _group_valid_rows(data: _Array) -> list[tuple[npt.NDArray[np.bool_], npt.NDArray[np.intp]]]: - """Group row indices by identical non-NaN masks.""" - grouped: dict[bytes, tuple[npt.NDArray[np.bool_], list[int]]] = {} - valid_masks = ~np.isnan(data) - for row_index, valid in enumerate(valid_masks): - key = valid.tobytes() - existing = grouped.get(key) - if existing is None: - grouped[key] = (valid.copy(), [row_index]) - else: - existing[1].append(row_index) - return [ - (valid, np.asarray(row_indices, dtype=np.intp)) for valid, row_indices in grouped.values() - ] + The batch columns follow R's ``contr.sum``: batch ``j`` is 1 in column ``j``, + and the last batch is -1 in every column, so the batch coefficients sum to + zero and removing them keeps each feature's mean over batches. + """ + labels, batch_idx = np.unique(batch, return_inverse=True) + n_batch = len(labels) + x_batch = np.zeros((batch.shape[0], n_batch - 1), dtype=np.float64) + for j in range(n_batch - 1): + x_batch[batch_idx == j, j] = 1.0 + x_batch[batch_idx == n_batch - 1, :] = -1.0 + design = np.hstack([np.ones((batch.shape[0], 1), dtype=np.float64), x_batch]) + return design, x_batch def remove_batch_effect( - data: _Array, - batch: _Array, -) -> _Array: + data: FloatArray, + batch: npt.ArrayLike, +) -> FloatArray: """Remove batch effects using a linear model (limma-style). - Per-cell NaN is handled per-feature by omitting NaN observations from - the OLS fit (matching R ``limma::removeBatchEffect`` behavior). - NaN stays in the same positions in the output. + Missing cells are left out of each feature's least-squares fit, as R + ``limma::removeBatchEffect`` does, and stay missing in the output. A + feature missing from a whole batch is handled differently from R; see + Returns. Parameters ---------- data : ndarray, shape (n_features, n_samples) Expression / abundance matrix. Per-cell NaN is allowed. - batch : ndarray, shape (n_samples,) - Integer batch labels. + batch : array_like, shape (n_samples,) + Batch label per sample: whole numbers, one batch per distinct value. Returns ------- ndarray, shape (n_features, n_samples) - Batch-corrected data. NaN positions from input are preserved. + Batch-corrected data. NaN positions from input are preserved. A + feature is fitted on the batches it has values in, with sum-to-zero + contrasts over those batches, so a batch it lacks does not shift its + level. A feature with values in one batch only, or with no more values + than batches it is observed in, keeps its raw values: its fit would + leave no residual and collapse it to one level. The log counts both. + Each feature is fitted alone, so a single feature is corrected, and a + batch of one sample takes that sample's whole deviation into its batch + term, so the sample lands on the feature's mean of batch means. Raises ------ ValueError - On wrong dimensionality or batch length mismatch. + On wrong dimensionality, batch length mismatch, batch labels that are + not whole numbers, or infinite values. Examples -------- @@ -83,103 +91,125 @@ def remove_batch_effect( >>> corrected.shape (20, 8) """ - data = np.asarray(data, dtype=np.float64) - batch = np.asarray(batch).ravel() + corrected, _ = _remove_batch_effect_with_reasons(data, batch) + return corrected - validate_limma_input(data, batch) - has_nan = np.isnan(data).any() - if not has_nan: - return _remove_batch_effect_dense(data, batch) +def _remove_batch_effect_with_reasons( + data: FloatArray, batch: npt.ArrayLike +) -> tuple[FloatArray, npt.NDArray[np.str_]]: + """Validate and correct as ``remove_batch_effect()`` does, and return why each feature was left raw. + The reason is an empty string for a corrected feature, otherwise + ``"no_values"``, ``"single_batch"``, or ``"too_few_values"`` (no more values + than batches it is observed in). + """ + data = np.asarray(data, dtype=np.float64) + batch_int = batch_codes(batch) + validate_engine_input(data, batch_int) + + if not np.isnan(data).any(): + return _remove_batch_effect_dense(data, batch_int) if np.isnan(data).all(): logger.debug("All-NaN input, returning copy") - return data.copy() + return data.copy(), np.full(data.shape[0], "no_values", dtype=" tuple[FloatArray, npt.NDArray[np.str_]]: + """limma correction fitted on each feature's observed cells. -def _remove_batch_effect_nan(data: _Array, batch: _Array) -> _Array: - """limma batch correction with per-feature NaN handling.""" - _, n_samples = data.shape - - unique_batches = np.unique(batch) - n_batch = len(unique_batches) + Features that share a pattern of observed cells are fitted together, with + contrasts over the batches they are observed in. A feature with values in + one batch only keeps its raw values, as does a feature whose values do not + outnumber its observed batches, since its fit would leave no residual and + collapse its values to one level. Returns the matrix and the reasons of + ``_remove_batch_effect_with_reasons``. + """ + reasons = np.full(data.shape[0], "", dtype=" _Array: - """Dense (NaN-free) limma-style batch correction. See ``remove_batch_effect``.""" - _, n_samples = data.shape - - unique_batches = np.unique(batch) - n_batch = len(unique_batches) + corrected[np.ix_(row_indices, valid_idx)] = group_data - beta_batch @ group_x.T + + if n_single_batch or n_no_residual: + logger.info( + "%d feature(s) left uncorrected: %d with values in a single batch, %d with no " + "more values than observed batches", + n_single_batch + n_no_residual, + n_single_batch, + n_no_residual, + ) + if n_no_values: + logger.debug("%d feature(s) with no value stay missing", n_no_values) + return corrected, reasons + + +def _remove_batch_effect_dense( + data: FloatArray, batch: npt.NDArray[np.intp] +) -> tuple[FloatArray, npt.NDArray[np.str_]]: + """limma correction of a matrix without missing cells. See ``remove_batch_effect``.""" + n_batch = len(np.unique(batch)) if n_batch < 2: logger.debug("Single batch input, returning copy") - return data.copy() - - # --- Sum-to-zero contrasts (R's contr.sum) --- - label_map = {b: i for i, b in enumerate(unique_batches)} - batch_idx = np.array([label_map[b] for b in batch], dtype=np.intp) - - X_batch = np.zeros((n_samples, n_batch - 1), dtype=np.float64) # noqa: N806 - for j in range(n_batch - 1): - X_batch[batch_idx == j, j] = 1.0 - X_batch[batch_idx == n_batch - 1, :] = -1.0 - - intercept = np.ones((n_samples, 1), dtype=np.float64) - design = np.hstack([intercept, X_batch]) - + return data.copy(), np.full(data.shape[0], "single_batch", dtype=" pd.DataFrame: """DataFrame wrapper around ``remove_batch_effect``. Parameters ---------- sub_df : DataFrame - Features x samples. Must not contain NaN. + Features x samples. Missing cells are allowed and stay missing. batch_labels : array-like - Integer batch label per sample (column). + Batch label per sample (column), whole numbers. Returns ------- @@ -189,7 +219,8 @@ def adjust_limma( Raises ------ ValueError - On NaN in *sub_df* or fewer than 2 batches. + If the batch labels are not whole numbers or do not match the number + of columns, or *sub_df* holds infinite values. Examples -------- diff --git a/src/harmonizepy/sorting.py b/src/harmonizepy/sorting.py index 48f29cf..0241f96 100644 --- a/src/harmonizepy/sorting.py +++ b/src/harmonizepy/sorting.py @@ -1,15 +1,10 @@ -"""Batch column sorting strategies for HarmonizePy. +"""Batch orders that place similar batches next to each other before blocking. -Sorting reorders **batch columns** (and their samples) in the data matrix -so that similar batches become neighbors. This only affects output when -combined with blocking. Adjacent batches are grouped into blocks, so -the ordering determines which batches share a block and therefore how -much data is lost when features are absent in one block member. - -Calling ``sort_batches`` without subsequently applying blocking has -no effect on adjusted values. - -This mirrors R ``HarmonizR:::sorting``. +Blocking groups neighbouring batches, so the order decides which batches share +a block, and how many values are lost where a feature is missing from one +batch of a block. Without blocking the order has no effect on corrected +values. The strategies follow R ``HarmonizR:::sorting``; how each of the three +orders differs from R's is listed in ``assets/FEATURE_PARITY.md``. """ from __future__ import annotations @@ -32,63 +27,58 @@ def sort_batches( strategy: str, needed_values: int, ) -> tuple[pd.DataFrame, npt.NDArray[np.integer], npt.NDArray[np.intp]]: - """Reorder data columns so that similar batches are adjacent. + """Reorder the columns so that similar batches are adjacent. - Computes a permutation of batches using *strategy*, then reorders the - sample columns (and the accompanying *batch_list*) to match. Call - this before blocking; call the returned ``col_order`` inverse after - ``rebuild`` to restore the original column ordering. - - .. note:: - Sorting without subsequent blocking leaves adjusted values - unchanged. The function is a no-op on output when ``block=None``. + A feature counts as present in a batch when it has at least + *needed_values* observed values there. ``"sparsity"`` puts batches with + more present features first; ``"jaccard"`` chains batches by the overlap of + their present features; ``"seriation"`` orders them by the first principal + component of their presence vectors. Samples keep their relative order + within a batch. Parameters ---------- data : DataFrame - Features x samples matrix. Columns are sample IDs; rows are - features. May contain NaN. + Features x samples matrix; missing cells are allowed. Not modified. batch_list : ndarray, shape (n_samples,) - Integer batch label per sample. - strategy : str - ``"sparsity"``, ``"jaccard"``, or ``"seriation"``. + Batch label of each column. + strategy : {"sparsity", "jaccard", "seriation"} + Ordering strategy. needed_values : int - Minimum non-NaN values per batch per feature for the feature to - count as "present" in that batch when building the binary - presence matrix used by all strategies. + Observed values a feature needs in a batch to count as present. Returns ------- sorted_data : DataFrame - Copy of *data* with columns reordered by the new batch order. - sorted_batch_list : ndarray - *batch_list* reordered to match the new column order. - col_order : ndarray of int, shape (n_samples,) - Original column indices for each position in *sorted_data*. - To restore the original column order after rebuild, use - ``result.iloc[:, np.argsort(col_order)]``. + A new frame with the columns in the new order. + sorted_batch_list : ndarray, shape (n_samples,) + *batch_list* in the new order. + col_order : ndarray of intp, shape (n_samples,) + The input column index at each position of *sorted_data*; + ``np.argsort(col_order)`` restores the input order. Raises ------ ValueError - If *strategy* is not one of the three accepted values. + If *strategy* is not one of the three names. Examples -------- + Batch 1 has values for 3 of 10 features, so ``"sparsity"`` moves it last: + >>> import numpy as np, pandas as pd >>> from harmonizepy.sorting import sort_batches - >>> rng = np.random.default_rng(0) >>> data = pd.DataFrame( - ... rng.standard_normal((10, 6)), - ... columns=["s1", "s2", "s3", "s4", "s5", "s6"], + ... np.arange(60.0).reshape(10, 6), columns=["s1", "s2", "s3", "s4", "s5", "s6"] ... ) - >>> batch = np.array([1, 1, 2, 2, 3, 3]) - >>> data.iloc[5:, 4:] = float("nan") # batch 3 has fewer present features - >>> sd, sb, co = sort_batches(data, batch, "sparsity", needed_values=2) - >>> sd.shape - (10, 6) - >>> list(sd.columns[:2]) # batch 3 (sparsest) is now first - ['s4', 's5'] + >>> data.iloc[3:, 0:2] = np.nan + >>> sorted_data, sorted_batches, col_order = sort_batches( + ... data, np.array([1, 1, 2, 2, 3, 3]), "sparsity", needed_values=2 + ... ) + >>> list(sorted_data.columns) + ['s3', 's4', 's5', 's6', 's1', 's2'] + >>> col_order.tolist() + [2, 3, 4, 5, 0, 1] """ if strategy not in _VALID_SORT_STRATEGIES: raise ValueError( @@ -110,7 +100,7 @@ def sort_batches( batch_order = _sparsity_order(presence) elif strategy == "jaccard": batch_order = _jaccard_order(presence) - else: # seriation + else: batch_order = _seriation_order(presence) ordered_batches = unique_batches[batch_order] @@ -134,10 +124,10 @@ def _build_presence_matrix( unique_batches: npt.NDArray[np.integer], needed_values: int, ) -> npt.NDArray[np.bool_]: - """Binary (n_features x n_batches) presence matrix. + """Return the (n_features, n_batches) matrix of features present in each batch. - ``presence[i, j] = True`` iff batch ``unique_batches[j]`` has at least - *needed_values* non-NaN observations for feature *i*. + Entry (i, j) is true when feature *i* has at least *needed_values* + observed values in batch ``unique_batches[j]``. """ values = data.to_numpy(dtype=np.float64) notna = ~np.isnan(values) @@ -169,85 +159,79 @@ def _column_order( def _sparsity_order(presence: npt.NDArray[np.bool_]) -> npt.NDArray[np.intp]: - """Sort batches descending by feature completeness count. + """Sort batches descending by the number of features present in each. - Batches with the most present features come first; batches with the - fewest come last. This mirrors R HarmonizR's ``find_na()``-based - sort which orders by ascending NA count (= descending completeness), - ensuring similar-completeness batches become neighbours under blocking. + Batches with the most present features come first; ties keep the order in + which the batches first appear in the columns. + R HarmonizR's ``find_na()`` counts the missing cells of each batch + instead, which ranks batches differently in general (see + ``assets/FEATURE_PARITY.md``). """ completeness = presence.sum(axis=0).astype(np.int64) return np.argsort(-completeness, kind="stable") def _jaccard_order(presence: npt.NDArray[np.bool_]) -> npt.NDArray[np.intp]: - """Greedy nearest-neighbour Jaccard ordering. + """Order batches by a greedy nearest-neighbour chain on Jaccard similarity. - Computes the pairwise Jaccard similarity matrix between batches via - vectorised integer matrix multiplication, then traverses batches - starting from the one with the highest total similarity to all others, - always picking the most similar unvisited batch next. + The similarity of two batches is the number of features present in both + divided by the number present in either, and 0 when neither has any. The + chain starts at the batch with the largest total similarity to the others + (the diagonal left out, since an empty batch has a self-similarity of 0, not + 1) and moves each time to the most similar batch not yet visited. """ - p = presence.astype(np.int32) # (n_features, n_batches) - # intersection[i, j] = number of features present in both batch i and j - intersection = (p.T @ p).astype(np.float64) # (n_batches, n_batches) - col_sums = presence.sum(axis=0).astype(np.float64) # (n_batches,) - # union[i, j] = |A| + |B| - |A ∩ B| - union = col_sums[:, None] + col_sums[None, :] - intersection + counts = presence.astype(np.int32) + intersection = (counts.T @ counts).astype(np.float64) + present_per_batch = presence.sum(axis=0).astype(np.float64) + union = present_per_batch[:, None] + present_per_batch[None, :] - intersection with np.errstate(invalid="ignore", divide="ignore"): jaccard = np.where(union > 0, intersection / union, 0.0) - n = jaccard.shape[0] - if n == 1: + n_batches = jaccard.shape[0] + if n_batches == 1: return np.array([0], dtype=np.intp) - # Start from the batch most similar (on average) to all others. - # Subtract the diagonal (self-similarity) rather than a constant 1: empty - # batches have jaccard[i,i]=0 due to the 0/0 guard above, not 1. - sim_sums = jaccard.sum(axis=1) - np.diag(jaccard) - start = int(np.argmax(sim_sums)) - - visited = np.zeros(n, dtype=np.bool_) + similarity_to_others = jaccard.sum(axis=1) - np.diag(jaccard) + start = int(np.argmax(similarity_to_others)) + visited = np.zeros(n_batches, dtype=np.bool_) order: list[int] = [start] visited[start] = True - - for _ in range(n - 1): - current = order[-1] - sims = jaccard[current].copy() - sims[visited] = -1.0 - nxt = int(np.argmax(sims)) - order.append(nxt) - visited[nxt] = True - + for _ in range(n_batches - 1): + candidates = jaccard[order[-1]].copy() + candidates[visited] = -1.0 + nearest = int(np.argmax(candidates)) + order.append(nearest) + visited[nearest] = True return np.array(order, dtype=np.intp) def _seriation_order(presence: npt.NDArray[np.bool_]) -> npt.NDArray[np.intp]: - """PCA-based seriation ordering (matches R ``seriation::seriate`` PCA method). - - Performs PCA on the batch presence vectors (batches as observations, - features as variables) and orders batches ascending by their first-PC - score. This replicates R's ``seriation::seriate(binary_df, margin=2)`` - default behaviour which uses ``prcomp(t(x), scale=FALSE)`` internally. - Sign is anchored so the batch with the largest absolute PC1 score is - positive (matching R's ``prcomp`` sign convention). + """Order batches by their score on the first principal component of presence. + + Batches are the observations and features the variables; the presence + matrix is centred per feature and not scaled, as ``prcomp(scale = FALSE)`` + does. The component is the leading eigenvector of the batches' Gram matrix, + which is computed exactly in integers, so the order does not depend on the + order of the features. Scores are rounded to 12 decimals of the unit + eigenvector before ordering, so batches whose scores differ only by + rounding tie, and ties keep the input order. The sign is fixed so that the + first batch with the largest absolute score is positive. When the two + largest eigenvalues are equal the component is not unique, and the one the + eigensolver returns for that exact matrix is used. With two batches or + fewer the input order is returned. R HarmonizR's seriation uses + ``seriation::seriate``, which gives a different order in general. """ - p = presence.T.astype(np.float64) # (n_batches, n_features) - n = p.shape[0] - - if n <= 2: - return np.arange(n, dtype=np.intp) - - # Centre columns (features) to mirror R's prcomp(t(binary_df), scale=FALSE) - p -= p.mean(axis=0) - - # SVD into PC1 scores for each batch - U, s, _Vt = np.linalg.svd(p, full_matrices=False) # noqa: N806 (standard SVD notation) - pc1 = U[:, 0] * s[0] - - # Sign convention: make the PC1 direction point "toward" the batch with - # the largest absolute score being positive (mirrors R prcomp convention). - if pc1[np.argmax(np.abs(pc1))] < 0: - pc1 = -pc1 - - return np.argsort(pc1, kind="stable") + n_batches = presence.shape[1] + if n_batches <= 2: + return np.arange(n_batches, dtype=np.intp) + counts = presence.astype(np.int64) + # n_batches times the centred presence, kept in integers so the Gram + # matrix below is exact and identical for any order of the features. + scaled = n_batches * counts - counts.sum(axis=1, keepdims=True) + gram = (scaled.T @ scaled).astype(np.float64) + _, vectors = np.linalg.eigh(gram) + scores = np.round(vectors[:, -1], 12) + largest = int(np.argmax(np.abs(scores))) + if scores[largest] < 0: + scores = -scores + return np.argsort(scores, kind="stable") diff --git a/src/harmonizepy/splitting.py b/src/harmonizepy/splitting.py index f33c105..08f6e70 100644 --- a/src/harmonizepy/splitting.py +++ b/src/harmonizepy/splitting.py @@ -1,12 +1,8 @@ -"""Data splitting and per-sub-frame adjustment. +"""Correction of each group of features that share an affiliation. -Groups features by their affiliation (missingness pattern), extracts -sub-matrices containing only the columns (samples) present for that -group, applies ComBat or limma adjustment, and returns the fully -assembled corrected DataFrame. - -This mirrors the split-and-rebuild effect of R ``HarmonizR:::splitting`` -without materializing one full-width DataFrame per affiliation group. +Each group's sub-matrix holds its features and the columns of its blocks; it +is corrected by ComBat or limma and written into one output matrix. This has +the effect of R ``HarmonizR:::splitting`` and its rebuild step. """ from __future__ import annotations @@ -18,9 +14,9 @@ import pandas as pd from .affiliation import reduce_to_unique_groups -from .combat import combat -from .combat_wrapper import _MODE_MAP -from .limma_wrapper import remove_batch_effect +from .combat import COMBAT_MODES, _combat_with_reasons +from .limma_wrapper import _remove_batch_effect_with_reasons +from .validation import validate_combat_mode logger = logging.getLogger(__name__) @@ -37,33 +33,39 @@ def splitting( output_columns: pd.Index | None = None, data_np: npt.NDArray[np.float64] | None = None, ) -> pd.DataFrame: - """Split data by affiliation, adjust each sub-frame, return result. + """Correct each group of features that share an affiliation, and assemble the result. Parameters ---------- - affiliation_list : list[tuple[int, ...]] - One tuple per feature (row), listing the block IDs where the feature - has sufficient data. From ``spotting.spotting_missing_values``. + affiliation_list : list of tuple of int + One affiliation per feature, as ``build_affiliation_list`` returns. data : DataFrame - Features x samples. - batch_list : ndarray - Batch label per sample (1-indexed). - block_list : ndarray - Block label per sample (equals batch_list when no blocking). - algorithm : str - ``"ComBat"`` or ``"limma"``. - combat_mode : int - ComBat mode 1-4 (ignored when algorithm is limma). - data_np : ndarray or None, keyword-only - Optional precomputed float64 view or copy of *data* with shape - ``(n_features, n_samples)``. When provided, reused instead of - converting *data* again inside this function. + Features x samples matrix; missing cells are allowed. Not modified. + batch_list : ndarray, shape (n_samples,) + Batch label of each column. + block_list : ndarray, shape (n_samples,) + Block label of each column; equal to *batch_list* without blocking. + algorithm : {"ComBat", "limma"} + Correction engine. + combat_mode : {1, 2, 3, 4} + ComBat mode; ignored for limma. + output_col_order : ndarray of intp, shape (n_samples,), optional + For each column of *data*, as sorted, the output column it is written + to, so that the result is in the order before sorting. + output_columns : Index, optional + Column labels of the output; defaults to ``data.columns``. + data_np : ndarray, shape (n_features, n_samples), optional + *data* as float64, reused instead of converting it again. Returns ------- DataFrame - Fully assembled corrected matrix. Features with empty affiliations - remain all-NaN to preserve completeness. + The corrected matrix with the index of *data*. A feature with an empty + affiliation is all missing. A feature alone in its group, or in a group + that spans one batch, keeps its raw values with either engine: one + batch has no batch effect to remove, ComBat cannot form a prior from + one feature, and limma would remove the feature's own batch means with + any true difference between batches. The log counts both kinds. Raises ------ @@ -82,19 +84,61 @@ def splitting( >>> result = splitting(affil, data, batch, batch, algorithm="ComBat", combat_mode=2) >>> result.shape (3, 4) + + Notes + ----- + One output array is allocated and filled group by group; sub-matrices are + extracted one group at a time. A group of one feature takes a shortcut + without matrix indexing, and a group that spans the whole matrix is read + without a copy. """ + corrected, _, _ = _correct_groups( + affiliation_list, + data, + batch_list, + block_list, + algorithm, + combat_mode, + output_col_order=output_col_order, + output_columns=output_columns, + data_np=data_np, + ) + return corrected + + +def _correct_groups( + affiliation_list: list[tuple[int, ...]], + data: pd.DataFrame, + batch_list: np.ndarray, + block_list: np.ndarray, + algorithm: str = "ComBat", + combat_mode: int = 1, + *, + output_col_order: npt.NDArray[np.intp] | None = None, + output_columns: pd.Index | None = None, + data_np: npt.NDArray[np.float64] | None = None, +) -> tuple[pd.DataFrame, npt.NDArray[np.str_], npt.NDArray[np.intp]]: + """Do the work of ``splitting()`` and also return each feature's outcome. + + Returns the corrected matrix, a reason per feature (empty when corrected; + ``"no_usable_batch"``, ``"single_batch"``, ``"alone_in_pattern"``, a + ComBat reason from ``_combat_validated``, or limma's ``"too_few_values"``), + and the size of each feature's + group (0 for an empty affiliation). + """ + if algorithm not in ("ComBat", "limma"): + raise ValueError(f"algorithm must be 'ComBat' or 'limma', got {algorithm!r}.") + if algorithm == "ComBat": + validate_combat_mode(combat_mode) + batch_arr = np.asarray(batch_list) block_arr = np.asarray(block_list) - # Convert to numpy once to avoid DataFrame overhead in the hot loop. if data_np is None: data_np = data.to_numpy(dtype=np.float64) - # Group features by affiliation using the shared reducer affil_to_features = reduce_to_unique_groups(affiliation_list) - # Cache sample indices once per block and affiliation to avoid - # rescanning block_arr for every unique group. block_to_cols: dict[int, list[int]] = {} for col_index, block_id in enumerate(block_arr.tolist()): block_to_cols.setdefault(int(block_id), []).append(col_index) @@ -116,58 +160,58 @@ def splitting( data.shape[1], ) - # Pre-allocate a single output array (n_features, n_samples) filled with NaN. - # This avoids allocating one full-width DataFrame per affiliation group, - # reducing peak memory from ~3x input to ~1x input. n_features, n_samples = data.shape output = np.full((n_features, n_samples), np.nan, dtype=np.float64) n_single_batch = 0 n_single_feature = 0 + reasons = np.full(n_features, "", dtype=" 0: logger.info( "%d feature(s) passed through without correction " - "(%d single-batch groups, %d single-feature groups)", + "(%d in single-batch groups, %d alone in their pattern)", n_uncorrected, n_single_batch, n_single_feature, ) - return pd.DataFrame( + corrected_frame = pd.DataFrame( output, index=data.index, columns=data.columns if output_columns is None else output_columns, copy=False, ) + return corrected_frame, reasons, group_sizes diff --git a/src/harmonizepy/types.py b/src/harmonizepy/types.py index 1db817f..e515c39 100644 --- a/src/harmonizepy/types.py +++ b/src/harmonizepy/types.py @@ -1,43 +1,50 @@ -"""Shared data structures for the HarmonizePy pipeline.""" +"""The run configuration and the array type shared by the engines.""" from __future__ import annotations from dataclasses import dataclass -from typing import Literal +from typing import Any, Literal, NamedTuple -from .validation import _validate_core_args +import numpy as np +import numpy.typing as npt +import pandas as pd + +from .validation import validate_core_args + +FloatArray = npt.NDArray[np.floating[Any]] @dataclass(frozen=True, slots=True) class HarmonizeConfig: - """Configuration for a single harmonization run. + """Settings for one run of ``harmonize()``, checked when created. + + The fields have the meaning and defaults of the ``harmonize()`` arguments + of similar name. Parameters ---------- - algorithm : str - ``"ComBat"`` or ``"limma"``. - combat_mode : int - ComBat mode 1-4 (ignored when *algorithm* is ``"limma"``). + algorithm : {"ComBat", "limma"} + Correction engine. + combat_mode : {1, 2, 3, 4} + ComBat mode; ignored for limma. needed_values : int or None - Minimum non-missing values per batch for a feature to be included. - ``None`` (default) auto-selects: 2 for modes 1, 3 and limma; 1 for - modes 2, 4. Mirrors the *needed_values* default in ``harmonize``. - sort_strategy : str or None - Batch sorting strategy: ``"sparsity"``, ``"jaccard"``, - ``"seriation"``, or ``None`` (no sort). + Minimum observed values per batch; ``None`` chooses 2 for limma and + modes 1 and 3, and 1 for modes 2 and 4. + sort_strategy : {"sparsity", "jaccard", "seriation"} or None + Batch order used to form blocks (``harmonize()``'s ``sort``). block_size : int or None - Number of consecutive batches to group into one block. Must be - >= 2 and < total number of unique batches. ``None`` disables - blocking. + Batches per block (``harmonize()``'s ``block``). Whether it is below + the number of batches is checked when the data are read. unique_removal : bool - When ``True`` (default), rescue singleton features whose batch - combination is unique by cropping to the nearest shared pattern. + Whether a feature with an affiliation of its own is moved into a + shared one. Raises ------ ValueError - On invalid *algorithm*, *combat_mode*, *needed_values*, - *sort_strategy*, or *block_size*. + On an unknown algorithm, ComBat mode, or sort strategy, a + ``needed_values`` that is not a whole number of at least 1, or a block + size that is not an integer of at least 2. TypeError If *unique_removal* is not a bool. @@ -60,7 +67,7 @@ class HarmonizeConfig: unique_removal: bool = True def __post_init__(self) -> None: - _validate_core_args( + validate_core_args( self.algorithm, self.combat_mode, self.needed_values, @@ -68,3 +75,14 @@ def __post_init__(self) -> None: self.block_size, self.unique_removal, ) + + +class HarmonizeResult(NamedTuple): + """The corrected matrix and the per-feature correction report of one run. + + Returned by ``harmonize(..., return_report=True)``; unpacks as + ``data, report``. + """ + + data: pd.DataFrame + report: pd.DataFrame diff --git a/src/harmonizepy/validation.py b/src/harmonizepy/validation.py index 68ae137..b1fec29 100644 --- a/src/harmonizepy/validation.py +++ b/src/harmonizepy/validation.py @@ -1,22 +1,75 @@ -"""Centralised input validation for HarmonizePy. - -Every public-facing validation check lives here so error messages are -consistent and the logic is not duplicated across modules. +"""Checks on the inputs of a run and of the engines. + +The data matrix, the batch description and its column rule, batch labels, +the ComBat mode, the reference batch, and the arguments of ``harmonize()`` +and ``HarmonizeConfig`` are checked here, so that each rule has one place and +one message. ``build_block_list`` and ``sort_batches`` repeat their argument +checks because they can be called on their own. ``check_input_scale`` warns +when the data do not look log-transformed. """ from __future__ import annotations -from typing import Any +import warnings +from collections.abc import Sequence +from typing import TYPE_CHECKING, Any import numpy as np import numpy.typing as npt import pandas as pd -_Array = npt.NDArray[np.floating[Any]] +if TYPE_CHECKING: + from .types import FloatArray + +# Every integer up to 2**53 is exact in float64; a float label at or beyond it +# may already have been rounded to a neighbouring integer. +_MAX_FLOAT_LABEL = 2.0**53 +_VALID_SORT_STRATEGIES: frozenset[str] = frozenset({"sparsity", "jaccard", "seriation"}) +_RAW_SCALE_P95 = 100.0 +_SCALE_SAMPLE = 100_000 + + +def _reject_infinite( + values: npt.NDArray[np.floating[Any]], names: Sequence[object] | pd.Index +) -> None: + """Raise ``ValueError`` if any value is infinite, naming the first features.""" + infinite_rows = np.flatnonzero(np.isinf(values).any(axis=1)) + if infinite_rows.size: + shown = [str(names[i]) for i in infinite_rows[:5]] + raise ValueError( + f"data contains infinite values in {infinite_rows.size} feature(s) " + f"(first: {shown}). Replace them with NaN; log2 of zero, for example, " + "gives -inf." + ) + + +# ComBat squares residuals and sums them per feature; values at or beyond this +# magnitude overflow float64 in those sums and turn the output non-finite. +COMBAT_MAX_ABS_VALUE = 1e150 + + +def reject_combat_overflow( + values: npt.NDArray[np.floating[Any]], names: Sequence[object] | pd.Index +) -> None: + """Raise ``ValueError`` if a value is too large for ComBat, naming the first features. + + ComBat's variance sums overflow float64 for magnitudes of about 1e154, which + makes its output non-finite; values at or beyond ``COMBAT_MAX_ABS_VALUE`` + are rejected. Log-scale data are many orders of magnitude below it. + """ + with np.errstate(invalid="ignore"): + large_rows = np.flatnonzero((np.abs(values) >= COMBAT_MAX_ABS_VALUE).any(axis=1)) + if large_rows.size: + shown = [str(names[i]) for i in large_rows[:5]] + raise ValueError( + f"data contains values of magnitude 1e150 or more in {large_rows.size} " + f"feature(s) (first: {shown}); ComBat's variance sums overflow at such values. " + "Log-transform the data, or use limma." + ) def validate_data_matrix(df: pd.DataFrame) -> None: - """Check that *df* is a valid features-x-samples matrix. + """Check that *df* is a features x samples matrix the engines can use. Parameters ---------- @@ -26,15 +79,15 @@ def validate_data_matrix(df: pd.DataFrame) -> None: Raises ------ ValueError - If *df* has duplicate row indices, all-NaN rows, fewer than - 2 columns, or non-numeric dtype. + If *df* has duplicate feature or sample names, fewer than 2 columns, + a non-numeric column, or infinite values. Examples -------- >>> import pandas as pd >>> from harmonizepy.validation import validate_data_matrix >>> df = pd.DataFrame({"s1": [1.0, 2.0], "s2": [3.0, 4.0]}) - >>> validate_data_matrix(df) # no error + >>> validate_data_matrix(df) """ dups = df.index[df.index.duplicated(keep=False)].unique().tolist() if dups: @@ -43,6 +96,15 @@ def validate_data_matrix(df: pd.DataFrame) -> None: f"{dups[:5]}). Each row must have a unique identifier." ) + # Sample names are matched to the description as text, so 1 and "1" collide. + sample_names = df.columns.astype(str) + repeated_samples = sample_names[sample_names.duplicated()].unique().tolist() + if repeated_samples: + raise ValueError( + f"data contains duplicate sample names: {repeated_samples[:5]}. " + "Each column must have a unique name." + ) + bad = df.dtypes[~df.dtypes.map(pd.api.types.is_numeric_dtype)].index.tolist() if bad: raise ValueError( @@ -56,6 +118,8 @@ def validate_data_matrix(df: pd.DataFrame) -> None: f"Batch correction requires samples from multiple batches." ) + _reject_infinite(df.to_numpy(dtype=np.float64, na_value=np.nan), df.index) + def validate_description(desc: pd.DataFrame, data: pd.DataFrame) -> None: """Check that a batch description matches a data matrix. @@ -63,15 +127,18 @@ def validate_description(desc: pd.DataFrame, data: pd.DataFrame) -> None: Parameters ---------- desc : DataFrame - Batch description with at least 3 columns (ID, sample, batch). + Batch description with at least 3 columns (ID, sample, batch). The ID + and batch columns are found by name when present, otherwise by + position (first and third). data : DataFrame Data matrix whose column names must match the IDs in *desc*. Raises ------ ValueError - If sample IDs do not match data columns or the description has - fewer than 3 columns. + If the description has fewer than 3 columns, its ID or batch column + cannot be found, it lists a sample ID more than once, its IDs do not + match the data columns, or a batch label is not a whole number. Examples -------- @@ -79,18 +146,16 @@ def validate_description(desc: pd.DataFrame, data: pd.DataFrame) -> None: >>> from harmonizepy.validation import validate_description >>> data = pd.DataFrame({"s1": [1.0], "s2": [2.0]}) >>> desc = pd.DataFrame({"ID": ["s1", "s2"], "sample": [1, 2], "batch": [1, 2]}) - >>> validate_description(desc, data) # no error + >>> validate_description(desc, data) """ - if desc.shape[1] < 3: + ids, batches = _description_columns(desc) + id_series = ids.astype(str) + repeated_ids = id_series[id_series.duplicated()] + if not repeated_ids.empty: raise ValueError( - f"description must have at least 3 columns (ID, sample, batch), " - f"got {desc.shape[1]}. Check the description file format." + f"sample IDs listed more than once in the description: " + f"{sorted(set(repeated_ids))[:5]}. Each sample must have one batch." ) - - if "ID" in desc.columns: - id_series = desc["ID"].astype(str) - else: - id_series = desc.iloc[:, 0].astype(str) desc_ids = set(id_series) data_ids = set(data.columns.astype(str)) @@ -104,88 +169,239 @@ def validate_description(desc: pd.DataFrame, data: pd.DataFrame) -> None: parts.append(f"in data but not description: {sorted(extra_data)[:5]}") raise ValueError( f"Sample IDs in description do not match data columns - {'; '.join(parts)}. " - f"The first column (or a column named 'ID') of description must list the exact column names of data." + f"The column named 'ID' (or else the first column) of description must list the " + f"exact column names of data." ) + _integer_labels(batches) -def validate_combat_input(data: _Array, batch: npt.NDArray[np.integer[Any]]) -> None: - """Check ndarray inputs for the ComBat engine. - Parameters - ---------- - data : ndarray, shape (n_features, n_samples) - Features x samples matrix. Per-cell NaN is allowed and handled - inside ``combat()`` via per-feature computations that omit only - the NaN observations for the feature being fitted. NaN positions - are preserved in the output. - batch : ndarray, shape (n_samples,) - Integer batch labels; length must equal the number of samples. +def _description_columns(desc: pd.DataFrame) -> tuple[pd.Series, pd.Series]: + """Return the sample ID and batch columns of a batch description. + + Each is found by name (``ID``, ``batch``) when present, otherwise by + position: the first column for IDs and the third for batches. Raises ------ ValueError - On wrong dimensionality or batch length mismatch. + If the description has fewer than 3 columns, or the ID and batch rules + point at the same column. + """ + if desc.shape[1] < 3: + raise ValueError( + f"description must have at least 3 columns (ID, sample, batch), " + f"got {desc.shape[1]}. Check the description file format." + ) + id_name = "ID" if "ID" in desc.columns else desc.columns[0] + batch_name = "batch" if "batch" in desc.columns else desc.columns[2] + if batch_name == id_name: + if id_name == "batch": + raise ValueError( + "the ID column cannot be found: the first column is the batch column. " + "Name the ID column 'ID'." + ) + raise ValueError( + "the batch column cannot be found: the third column is the ID column. " + "Name the batch column 'batch'." + ) + return desc[id_name], desc[batch_name] - Examples - -------- - >>> import numpy as np - >>> from harmonizepy.validation import validate_combat_input - >>> data = np.ones((5, 4)) - >>> validate_combat_input(data, np.array([0, 0, 1, 1])) # no error + +def _not_whole(values: npt.NDArray[np.float64]) -> npt.NDArray[np.bool_]: + """Mark labels that are missing, infinite, fractional, or too large to be exact. + + Float labels must lie below 2**53 in magnitude, the range in which float64 + holds every integer exactly. """ - if data.ndim != 2: - raise ValueError(f"data must be a 2-D array (features x samples), got {data.ndim}-D.") + bad: npt.NDArray[np.bool_] = ( + ~np.isfinite(values) | (values != np.round(values)) | (np.abs(values) >= _MAX_FLOAT_LABEL) + ) + return bad - _, n_samples = data.shape - if batch.shape[0] != n_samples: +def _shown_labels(labels: Sequence[object]) -> str: + """Return up to five distinct labels, quoted, for an error message.""" + distinct = list(dict.fromkeys(repr(label) for label in labels)) + return ", ".join(distinct[:5]) + (", ..." if len(distinct) > 5 else "") + + +def _integer_labels(batches: pd.Series) -> npt.NDArray[np.int64]: + """Return a description's batch labels as integers. + + Integer columns are used as they are. Other columns are read as numbers and + must hold whole numbers below 2**53 in magnitude. + + Raises + ------ + ValueError + If a label is missing, not numeric, not a whole number, or out of range, + naming the column and the offending values. + """ + numeric = pd.to_numeric(batches, errors="coerce") + if pd.api.types.is_signed_integer_dtype(numeric.dtype) and not numeric.isna().any(): + return numeric.to_numpy(dtype=np.int64) + values = numeric.to_numpy(dtype=np.float64, na_value=np.nan) + bad = _not_whole(values) + if bad.any(): raise ValueError( - f"batch length ({batch.shape[0]}) does not match the number of " - f"sample columns in data ({n_samples})." + f"batch labels in column {batches.name!r} must be whole numbers below 2**53 " + f"in magnitude; found {_shown_labels(batches[bad].tolist())}." + ) + return values.astype(np.int64) + + +def batch_codes(batch: npt.ArrayLike) -> npt.NDArray[np.intp]: + """Return engine batch labels as integers, rejecting labels that are not whole numbers. + + Parameters + ---------- + batch : array_like, shape (n_samples,) + One label per sample: integers of any width, booleans, or floats and + numeric strings with whole values below 2**53 in magnitude, such as 1.0. + + Returns + ------- + ndarray of intp, shape (n_samples,) + The labels as integers, in the input order. + + Raises + ------ + ValueError + If a label is text that is not a number, complex, missing, infinite, + fractional, or a float at least 2**53 in magnitude, naming the offending + labels. + """ + labels = np.asarray(batch).ravel() + if labels.dtype.kind in "iub": + return labels.astype(np.intp) + if labels.dtype.kind == "c": + values = np.full(labels.shape, np.nan) + else: + try: + values = labels.astype(np.float64) + except (TypeError, ValueError): + values = np.full(labels.shape, np.nan) + bad = _not_whole(values) + if bad.any(): + raise ValueError( + "batch labels must be whole numbers below 2**53 in magnitude; " + f"found {_shown_labels(labels[bad].tolist())}." ) + return values.astype(np.intp) -def validate_limma_input(data: _Array, batch: _Array) -> None: - """Check ndarray inputs for the limma engine. +def validate_engine_input(data: FloatArray, batch: npt.NDArray[np.integer[Any]]) -> None: + """Check the matrix and batch labels passed to ``combat()`` or ``remove_batch_effect()``. + + Missing cells are allowed: both engines fit each feature on its observed + cells and keep missing cells missing. Parameters ---------- data : ndarray, shape (n_features, n_samples) - Features x samples matrix. Per-cell NaN is allowed and handled - inside ``remove_batch_effect()`` via per-feature fits that omit - only the NaN observations for the feature being fitted. NaN - positions are preserved in the output. + Features x samples matrix. batch : ndarray, shape (n_samples,) - Integer batch labels; length must equal the number of samples. + Integer batch labels, as ``batch_codes`` returns them. Raises ------ ValueError - On wrong dimensionality or batch length mismatch. + If *data* is not 2-D, *batch* does not have one label per sample, or + *data* holds infinite values. Examples -------- >>> import numpy as np - >>> from harmonizepy.validation import validate_limma_input - >>> data = np.ones((5, 4)) - >>> validate_limma_input(data, np.array([0, 0, 1, 1])) # no error + >>> from harmonizepy.validation import validate_engine_input + >>> validate_engine_input(np.ones((5, 4)), np.array([0, 0, 1, 1])) """ if data.ndim != 2: raise ValueError(f"data must be a 2-D array (features x samples), got {data.ndim}-D.") - - _, n_samples = data.shape - + n_samples = data.shape[1] if batch.shape[0] != n_samples: raise ValueError( f"batch length ({batch.shape[0]}) does not match the number of " f"sample columns in data ({n_samples})." ) + _reject_infinite(data, range(data.shape[0])) -_VALID_SORT_STRATEGIES: frozenset[str] = frozenset({"sparsity", "jaccard", "seriation"}) +def validate_combat_mode(mode: object) -> None: + """Check that *mode* is one of the ComBat modes, an integer from 1 to 4. + + Modes 1 and 2 are parametric, 3 and 4 non-parametric; 1 and 3 adjust + location and scale, 2 and 4 location only. NumPy integers are accepted; + booleans and floats are not, even when they compare equal to a mode. + + Raises + ------ + ValueError + If *mode* is not an integer from 1 to 4. + """ + is_integer = isinstance(mode, (int, np.integer)) and not isinstance(mode, (bool, np.bool_)) + if not is_integer or mode not in (1, 2, 3, 4): + raise ValueError( + f"combat_mode must be 1, 2, 3, or 4, got {mode!r}. " + "Modes 1/2 are parametric; 3/4 are non-parametric. " + "Modes 1/3 adjust location+scale; 2/4 adjust location only." + ) + + +def validate_ref_batch(batch: npt.NDArray[np.integer[Any]], ref_batch: int | None) -> None: + """Check that a reference batch is one of the labels and has at least two samples. + + The pooled variance comes from the reference batch alone, so a single + sample leaves nothing to pool. + + Raises + ------ + ValueError + If *ref_batch* is not among the labels, or labels a single sample. + """ + if ref_batch is None: + return + labels = sorted(set(batch.tolist())) + if ref_batch not in labels: + raise ValueError(f"ref_batch={ref_batch!r} not found in batch labels {labels}") + if int(np.sum(batch == ref_batch)) < 2: + raise ValueError( + f"ref_batch={ref_batch!r} has a single sample; a reference batch needs at least two." + ) + + +def sample_batch_map(desc: pd.DataFrame) -> dict[str, int]: + """Map each sample ID to its integer batch label. + + The ID and batch columns are found as in ``validate_description``: by the + names ``ID`` and ``batch`` when present, otherwise the first column holds + the IDs and the third holds the batch labels. + + Parameters + ---------- + desc : DataFrame + Batch description with at least three columns. + Returns + ------- + dict[str, int] + Sample ID to batch label. -def _validate_core_args( + Raises + ------ + ValueError + If the description has fewer than 3 columns, its ID or batch column + cannot be found, it lists a sample ID more than once, or a batch label + is not a whole number. + """ + ids, batches = _description_columns(desc) + id_series = ids.astype(str) + if id_series.duplicated().any(): + raise ValueError("sample IDs listed more than once in the description.") + return dict(zip(id_series, _integer_labels(batches).tolist(), strict=True)) + + +def validate_core_args( algorithm: str, combat_mode: int, needed_values: int | None, @@ -193,26 +409,39 @@ def _validate_core_args( block_size: int | None = None, unique_removal: bool = True, ) -> None: - """Validate core parameter constraints shared by HarmonizeConfig and harmonize().""" + """Check the arguments shared by ``HarmonizeConfig`` and ``harmonize()``. + + Raises + ------ + ValueError + On an unknown algorithm, ComBat mode, or sort strategy, a + ``needed_values`` that is not a whole number of at least 1 (booleans + and floats are rejected), or a block size that is not an integer of at + least 2. + TypeError + If *unique_removal* is not a bool. + """ if algorithm not in ("ComBat", "limma"): raise ValueError(f"algorithm must be 'ComBat' or 'limma', got {algorithm!r}.") - if combat_mode not in (1, 2, 3, 4): - raise ValueError( - f"combat_mode must be 1, 2, 3, or 4, got {combat_mode}. " - f"Modes 1/2 are parametric; 3/4 are non-parametric. " - f"Modes 1/3 adjust location+scale; 2/4 adjust location only." - ) - if needed_values is not None and needed_values < 1: - raise ValueError( - f"needed_values must be >= 1 or None, got {needed_values}. " - f"Use needed_values=None to auto-select based on algorithm." + validate_combat_mode(combat_mode) + if needed_values is not None: + is_integer = isinstance(needed_values, (int, np.integer)) and not isinstance( + needed_values, (bool, np.bool_) ) + if not is_integer or needed_values < 1: + raise ValueError( + f"needed_values must be a whole number of at least 1, or None, got " + f"{needed_values!r}. Use needed_values=None to auto-select based on algorithm." + ) if sort_strategy is not None and sort_strategy not in _VALID_SORT_STRATEGIES: raise ValueError( f"sort must be one of {sorted(_VALID_SORT_STRATEGIES)!r} or None, " f"got {sort_strategy!r}." ) - if block_size is not None and (not isinstance(block_size, int) or block_size < 2): + is_block_integer = isinstance(block_size, (int, np.integer)) and not isinstance( + block_size, (bool, np.bool_) + ) + if block_size is not None and (not is_block_integer or block_size < 2): raise ValueError( f"block must be an integer >= 2 or None, got {block_size!r}. " f"Use block=None to disable blocking." @@ -249,7 +478,7 @@ def validate_harmonize_args( Block size; must be ``None`` or an integer >= 2. If *n_batches* is provided it must also be strictly less than *n_batches*. unique_removal : bool - Singleton-rescue toggle; must be a ``bool``. + Whether unique removal runs; must be a ``bool``. n_batches : int or None Number of unique batches in the data. When provided, validates ``block_size < n_batches``. @@ -265,11 +494,11 @@ def validate_harmonize_args( Examples -------- >>> from harmonizepy.validation import validate_harmonize_args - >>> validate_harmonize_args("ComBat", 2, 2) # no error + >>> validate_harmonize_args("ComBat", 2, 2) >>> validate_harmonize_args("ComBat", 1, 2, sort_strategy="sparsity", - ... block_size=2, n_batches=4) # no error + ... block_size=2, n_batches=4) """ - _validate_core_args( + validate_core_args( algorithm, combat_mode, needed_values, sort_strategy, block_size, unique_removal ) if n_batches is not None and block_size is not None and block_size >= n_batches: @@ -277,3 +506,70 @@ def validate_harmonize_args( f"block ({block_size}) must be less than the number of unique batches " f"({n_batches}). Each block needs at least two batches to be meaningful." ) + + +class InputScaleWarning(UserWarning): + """The data matrix looks like it is not on the log scale ComBat and limma expect. + + Silence it with ``warnings.filterwarnings("ignore", category=InputScaleWarning)``. + """ + + +def check_input_scale(values: FloatArray) -> None: + """Warn when the observed values look untransformed. + + ComBat and limma model batch effects as additive on the scale they receive, + so they expect log-transformed values, usually log2. This is a heuristic on + the observed cells only: + + - every value is non-negative and the 95th percentile is above + ``_RAW_SCALE_P95`` (100), as for raw intensities or counts. Log2 + intensities and log2 counts stay below about 35; + - every value lies in [0, 1] with more than two distinct values, as for + proportions such as methylation beta values. Binary and constant data are + left alone. + + The percentile is taken on whole rows at a fixed step, about + ``_SCALE_SAMPLE`` values in total, so that every column is represented and + the check stays cheap on large matrices. Percentages from 0 to 100 and + data with a single negative value are not detected. + + Parameters + ---------- + values : ndarray, shape (n_features, n_samples) + The data matrix. Missing cells are ignored. + + Warns + ----- + InputScaleWarning + Once, naming the pattern found and the transform to apply. + """ + if values.size == 0: + return + flat = values.ravel(order="K") + low = float(np.fmin.reduce(flat)) + if np.isnan(low) or low < 0.0: + return + high = float(np.fmax.reduce(flat)) + n_rows, n_cols = values.shape + step = max(1, n_rows // max(1, _SCALE_SAMPLE // max(n_cols, 1))) + sample = values[::step].ravel() + sample = sample[~np.isnan(sample)] + if sample.size and float(np.percentile(sample, 95)) > _RAW_SCALE_P95: + warnings.warn( + "the data look untransformed: every value is non-negative and the 95th " + f"percentile is above {_RAW_SCALE_P95:g}. ComBat and limma expect " + "log-transformed values: apply log2(x + 1) when the data contain zeros, " + "log2(x) otherwise. This check is a heuristic.", + InputScaleWarning, + stacklevel=4, + ) + elif high <= 1.0 and np.unique(sample).size > 2: + warnings.warn( + "the data look like proportions: every value lies between 0 and 1. ComBat " + "and limma assume values that can vary freely; for methylation beta " + "values, run the correction on M-values, log2(beta / (1 - beta)), and " + "convert back to beta. This check is a heuristic.", + InputScaleWarning, + stacklevel=4, + ) diff --git a/tests/fixtures/generate_blocking_fixtures.R b/tests/fixtures/generate_blocking_fixtures.R index 3b9c465..8960571 100644 --- a/tests/fixtures/generate_blocking_fixtures.R +++ b/tests/fixtures/generate_blocking_fixtures.R @@ -1,5 +1,5 @@ #!/usr/bin/env Rscript -# Generate R fixtures for Phase 2: blocking, sorting, and unique-removal. +# Generate R fixtures for blocking, sorting, and unique removal. # # Run from the project root: # Rscript tests/fixtures/generate_blocking_fixtures.R diff --git a/tests/fixtures/generate_edgecase_fixtures.R b/tests/fixtures/generate_edgecase_fixtures.R index a75b502..47a5bde 100644 --- a/tests/fixtures/generate_edgecase_fixtures.R +++ b/tests/fixtures/generate_edgecase_fixtures.R @@ -434,8 +434,8 @@ cat("\n=== Edge-case fixture generation complete ===\n") # ======================================================================= # 12. PER-CELL NaN: some features have stochastic per-cell NaN within # qualifying blocks, others are fully present. -# This tests na.omit behavior in sva::ComBat and matches real -# proteomics dropout patterns (e.g., murine_medulloblastoma). +# This tests sva::ComBat's per-feature handling of missing cells +# (Beta.NA), the dropout pattern of real proteomics data. # ======================================================================= cat("\n--- percell_nan (30x9, 3 batches of 3, per-cell NaN within blocks) ---\n") set.seed(888) @@ -463,8 +463,9 @@ desc_pcnan <- data.frame( write.csv(desc_pcnan, file.path(out_dir, "percell_nan_batch.csv"), row.names = FALSE) # Run HarmonizR pipeline on per-cell NaN data. -# R sva::ComBat drops the 10 rows with NaN and adjusts the 20 clean rows. -# Our Python keeps the 10 NaN rows as all-NaN and adjusts the 20 clean rows. +# Each of the 10 rows with a missing cell keeps two values per batch, so it +# stays in its group and is corrected on its observed cells; the missing +# cells stay missing. for (m in 1:4) { tryCatch({ result <- harmonizR( diff --git a/tests/test_api.py b/tests/test_api.py index d179464..d7df38a 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -17,6 +17,8 @@ import pandas as pd import pytest +from harmonizepy.core import harmonize + FIXTURE_DIR = Path(__file__).parent / "fixtures" _has_fixtures = (FIXTURE_DIR / "small_input.tsv").exists() @@ -707,3 +709,101 @@ def test_config_needed_values_none_auto_selects(self, small_inputs): result_cfg = harmonize(data, desc, config=cfg) result_kw = harmonize(data, desc) pd.testing.assert_frame_equal(result_cfg, result_kw) + + +class TestPathAndFrameInput: + """A file path and the same matrix as a DataFrame give the same result.""" + + def test_blank_row_kept_for_both_inputs(self, tmp_path: Path) -> None: + """A row with no value is kept as missing for a path and for a frame. + + Failure condition: the reader drops the blank row and the two outputs have + different rows. + """ + rng = np.random.default_rng(13) + samples = [f"s{i}" for i in range(1, 7)] + data = pd.DataFrame( + rng.normal(10, 1, (4, 6)), index=[f"p{i}" for i in range(4)], columns=samples + ) + data.loc["blank"] = np.nan + desc = pd.DataFrame({"ID": samples, "sample": range(1, 7), "batch": [1, 1, 1, 2, 2, 2]}) + data_path = tmp_path / "data.tsv" + data.to_csv(data_path, sep="\t") + from_path = harmonize(data_path, desc) + from_frame = harmonize(data, desc) + pd.testing.assert_frame_equal(from_path, from_frame, check_names=False) + assert from_path.loc["blank"].isna().all() + + +def test_unique_removal_logs_moved_features(caplog: pytest.LogCaptureFixture) -> None: + """When unique removal moves a feature into a shared pattern, the log says so. + + Failure condition: the count compares empty affiliations, which unique removal + never changes, so the message never appears. + """ + import logging + + samples = [f"s{i}" for i in range(1, 7)] + rows = [[1.0 + i, 1.5 + i, 2.1 + i, 2.4 + i, np.nan, np.nan] for i in range(4)] + rows.append([1.0, 1.4, 2.0, 2.6, 3.1, 3.5]) + data = pd.DataFrame(rows, index=[f"p{i}" for i in range(5)], columns=samples) + desc = pd.DataFrame({"ID": samples, "sample": range(1, 7), "batch": [1, 1, 2, 2, 3, 3]}) + with caplog.at_level(logging.INFO, logger="harmonizepy.core"): + harmonize(data, desc) + assert "Unique removal moved 1 feature(s) into a shared pattern" in caplog.text + + +class TestArgumentTypes: + """Inputs given as natural Python or NumPy values are accepted.""" + + def test_integer_column_labels_match_text_ids(self) -> None: + """A frame with integer column labels runs against text IDs 1 to 6. + + Failure condition: the batch lookup uses the raw label, so the integer + 1 is not found among the text IDs and a KeyError escapes after + validation passed. + """ + df, desc = _make_df_and_desc(n_features=10, n_per_batch=2, n_batches=3) + labels = list(range(1, df.shape[1] + 1)) + int_df = df.set_axis(labels, axis=1) + text_desc = desc.assign(ID=[str(label) for label in labels]) + + result = harmonize(int_df, text_desc) + expected = harmonize(df, desc) + + assert result.columns.tolist() == labels + np.testing.assert_allclose(result.to_numpy(), expected.to_numpy(), rtol=0, atol=0) + + def test_numpy_integer_block_is_accepted(self) -> None: + """block=np.int64(2) gives the same result as block=2. + + Failure condition: the block check accepts only Python int and + refuses a NumPy integer that needed_values accepts. + """ + df, desc = _make_df_and_desc(n_features=10, n_per_batch=3, n_batches=3) + + result = harmonize(df, desc, block=np.int64(2)) + + pd.testing.assert_frame_equal(result, harmonize(df, desc, block=2)) + + def test_boolean_block_is_refused(self) -> None: + """block=True is refused although bool is a subclass of int. + + Failure condition: the NumPy integer check lets booleans through. + """ + df, desc = _make_df_and_desc(n_features=10, n_per_batch=3, n_batches=3) + + with pytest.raises(ValueError, match="block must be an integer"): + harmonize(df, desc, block=True) + + def test_sample_names_equal_as_text_are_refused(self) -> None: + """Columns 1 and "1" are one sample name to the description and are refused. + + Failure condition: the two labels pass the duplicate check and map to + the same description row. + """ + df, desc = _make_df_and_desc(n_features=10, n_per_batch=2, n_batches=2) + df = df.set_axis([1, "1", 3, 4], axis=1) + + with pytest.raises(ValueError, match="duplicate sample names"): + harmonize(df, desc) diff --git a/tests/test_benchmarks.py b/tests/test_benchmarks.py index 4b52514..ff996f1 100644 --- a/tests/test_benchmarks.py +++ b/tests/test_benchmarks.py @@ -9,12 +9,14 @@ from pathlib import Path import pandas as pd +import pytest from benchmarks.harness import BenchmarkHarness from benchmarks.metrics import SingleRunMetrics, aggregate_metrics, assess_rss_stability from benchmarks.report import build_report_json, generate_markdown from benchmarks.runners import python_runner from benchmarks.scenarios import Config, DatasetSpec, Scenario +from benchmarks.validity import ValidityResult def _make_input() -> tuple[pd.DataFrame, pd.DataFrame]: @@ -364,8 +366,8 @@ class TestBenchmarkReport: def test_report_uses_post_gc_python_rss_fields(self) -> None: """Report JSON should expose retained post-GC Python RSS metrics. - Failure condition: the report only keeps the old raw delta and drops the - normalized RSS values needed for repeated-run interpretation. + Failure condition: the report keeps only the raw before/after delta and + drops the normalized RSS values needed for repeated-run interpretation. """ cfg = _make_config() scenario = Scenario(dataset="tiny", algorithm="limma") @@ -485,3 +487,91 @@ def fake_load_dataset(paths): assert data_df is expected_data assert desc_df is expected_desc + + +class TestReportSystemInfo: + """The report records the run's environment as it was.""" + + def test_blas_threads_follow_the_environment(self, monkeypatch: pytest.MonkeyPatch) -> None: + """The recorded BLAS thread limit is the one the environment sets. + + Failure condition: the report states the core count whatever the limit is. + """ + from benchmarks.report import _blas_threads_setting + + for name in ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv("OMP_NUM_THREADS", "1") + assert _blas_threads_setting() == "1" + monkeypatch.delenv("OMP_NUM_THREADS") + assert _blas_threads_setting().startswith("not limited") + + def test_cpu_model_is_named(self) -> None: + """The CPU field holds a model name, not an empty string. + + Failure condition: ``platform.processor()`` is empty on Linux and the + report says "unknown". + """ + from benchmarks.report import _cpu_model + + assert _cpu_model().strip() + + def test_markdown_header_prints_the_recorded_values(self) -> None: + """The Markdown header shows the recorded BLAS limit and package version. + + Failure condition: the header re-detects the threads when it is rendered. + """ + from benchmarks.report import generate_markdown + + report = { + "system": { + "os": "Linux", + "cpu": "test cpu", + "blas_threads": "1", + "python": "3.12", + "harmonizepy": "9.9.9", + }, + "results": [], + } + md = generate_markdown(report) + assert "BLAS threads=1" in md + assert "harmonizepy v9.9.9" in md + + +def test_report_json_keeps_feature_counts_of_one_side() -> None: + """The report JSON carries the features only Python or only R returned. + + Failure condition: the serializer drops the two counts, so the report's + "Py Only" and "R Only" columns are always blank. + """ + metrics = SingleRunMetrics( + elapsed_s=0.2, + cpu_pct=20.0, + tracemalloc_peak_mb=2.0, + rss_before_kb=100, + rss_after_kb=140, + rss_post_gc_kb=110, + rss_delta_kb=40, + rss_delta_post_gc_kb=10, + result={"n_total": 8, "n_corrected": 5, "n_passthrough": 3}, + ) + validity = ValidityResult(scenario_id="tiny_limma") + validity.concordance_shared_features = 5 + validity.concordance_py_only_features = 3 + validity.concordance_r_only_features = 1 + + report = build_report_json( + [ + ( + Scenario(dataset="tiny", algorithm="limma"), + aggregate_metrics([metrics]), + validity, + None, + ) + ], + _make_config(), + ) + + entry = report["results"][0]["validity"] + assert entry["concordance_py_only_features"] == 3 + assert entry["concordance_r_only_features"] == 1 diff --git a/tests/test_blocking.py b/tests/test_blocking.py index 697c558..c3b0a71 100644 --- a/tests/test_blocking.py +++ b/tests/test_blocking.py @@ -6,7 +6,7 @@ 2. TestBlockListValues: exact output for hand-crafted inputs 3. TestEdgeCases: minimum block_size=2, non-contiguous batch IDs 4. TestValidation: ValueError on bad block_size -5. TestHelperFunctions: _unique_ordered +5. TestUniqueOrdered: _unique_ordered """ from __future__ import annotations @@ -252,7 +252,7 @@ def test_block_size_exceeds_n_batches_raises(self): # --------------------------------------------------------------------------- -# 5. TestHelperFunctions +# 5. TestUniqueOrdered # --------------------------------------------------------------------------- @@ -280,3 +280,34 @@ def test_single_element(self): """ arr = np.array([5, 5, 5]) assert _unique_ordered(arr) == [5] + + +def test_block_count_logged_for_non_contiguous_labels(caplog: pytest.LogCaptureFixture) -> None: + """The log reports the number of blocks, also when a batch reappears at the end. + + Failure condition: the count is taken from the last sample's block. + """ + import logging + + with caplog.at_level(logging.DEBUG, logger="harmonizepy.blocking"): + build_block_list(np.array([1, 1, 2, 2, 3, 3, 1, 1]), block_size=2) + assert "Built 2 blocks" in caplog.text + + +def test_float_labels_are_blocked_by_first_appearance() -> None: + """Float batch labels are grouped by first appearance, like integers. + + Failure condition: a label that is not a whole number raises ``KeyError``. + """ + blocks = build_block_list(np.array([0.2, 0.2, 0.7, 1.0, 2.0, 0.7]), block_size=2) + np.testing.assert_array_equal(blocks, [1, 1, 1, 2, 2, 1]) + + +def test_float_labels_are_counted_as_distinct_batches() -> None: + """Float labels that differ only after the decimal point are separate batches. + + Failure condition: casting labels to int merges 0.2 and 0.7, so three batches + count as two and a block size of 2 is rejected. + """ + blocks = build_block_list(np.array([0.2, 0.2, 0.7, 0.7, 1.5, 1.5]), block_size=2) + np.testing.assert_array_equal(blocks, [1, 1, 1, 1, 2, 2]) diff --git a/tests/test_cli.py b/tests/test_cli.py index 9acb9ac..f3f2b08 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -8,8 +8,10 @@ import json import re +import warnings from pathlib import Path +import numpy as np import pandas as pd import pytest @@ -613,7 +615,7 @@ def test_invalid_sort_strategy(self) -> None: assert exc_info.value.code != 0 def test_block_lt_2_exits_nonzero(self, tmp_path: Path) -> None: - """block=1 fails validation inside harmonize → exit 1.""" + """block=1 fails validation inside harmonize gives exit 1.""" with pytest.raises(SystemExit) as exc_info: main([DATA, BATCH, "-o", str(tmp_path / "r.tsv"), "--block", "1"]) assert exc_info.value.code == 1 @@ -907,7 +909,7 @@ def test_config_dry_run_exits_zero(self, tmp_path: Path) -> None: # =========================================================================== -# All-flags smoke test (plan §2.5 test_cli_all_flags) +# Every option at once # =========================================================================== @@ -990,3 +992,342 @@ def test_all_flags_matches_api(self, tmp_path: Path) -> None: unique_removal=True, ) pd.testing.assert_frame_equal(cli, api, atol=1e-10) + + +_SMALL_DATA: str = ( + "id\ts1\ts2\ts3\ts4\ts5\ts6\n" + "p1\t1.0\t2.0\t3.0\t4.0\t5.0\t6.5\n" + "p2\t2.0\t2.5\t3.1\t4.2\t5.1\t6.0\n" + "p3\t1.5\t2.7\t3.3\t3.9\t5.5\t6.9\n" + "p4\t0.9\t2.2\t3.6\t4.1\t4.8\t6.2\n" +) +_DESC_ORDERS: dict[str, str] = { + "ID, sample, batch": "ID,sample,batch\n" + + "".join(f"s{i},{i},{1 if i <= 3 else 2}\n" for i in range(1, 7)), + "sample, ID, batch": "sample,ID,batch\n" + + "".join(f"{i},s{i},{1 if i <= 3 else 2}\n" for i in range(1, 7)), + "ID, batch, sample": "ID,batch,sample\n" + + "".join(f"s{i},{1 if i <= 3 else 2},{i}\n" for i in range(1, 7)), +} + + +def _small_inputs( + tmp_path: Path, desc_text: str = _DESC_ORDERS["ID, sample, batch"] +) -> tuple[str, str]: + data = tmp_path / "data.tsv" + data.write_text(_SMALL_DATA, encoding="utf-8") + desc = tmp_path / "desc.csv" + desc.write_text(desc_text, encoding="utf-8") + return str(data), str(desc) + + +class TestCLICsvDefaultName: + """The default output name follows --output-format.""" + + def test_csv_without_output_writes_csv_file(self, tmp_path: Path) -> None: + """With --output-format csv and no -o, a comma-separated .csv file is written. + + Failure condition: CSV text is written into a file named .tsv. + """ + from harmonizepy.__main__ import main + + data, desc = _small_inputs(tmp_path) + main([data, desc, "--output-format", "csv", "-q"]) + written = tmp_path / "data_corrected.csv" + assert written.exists() + assert not (tmp_path / "data_corrected.tsv").exists() + assert written.read_text(encoding="utf-8").splitlines()[0].count(",") == 6 + + def test_posix_path_with_colon_stays_posix(self) -> None: + """A POSIX path whose second character is a colon keeps its directory. + + Failure condition: the path is read as a Windows drive path and the output + lands in the working directory under a name with a backslash. + """ + from harmonizepy.__main__ import _resolve_output_path + + assert _resolve_output_path("a:b/data.tsv", None) == "a:b/data_corrected.tsv" + assert _resolve_output_path("C:\\x\\data.tsv", None) == "C:\\x\\data_corrected.tsv" + + +class TestCLIDryRunWritesNoFiles: + """A dry run writes no files.""" + + def test_dry_run_writes_no_log_file(self, tmp_path: Path) -> None: + """A dry run creates neither the output nor a log file. + + Failure condition: a log is written next to an output that is never created. + """ + from harmonizepy.__main__ import main + + data, desc = _small_inputs(tmp_path) + main([data, desc, "--dry-run"]) + assert not list(tmp_path.glob("*.log")) + assert not (tmp_path / "data_corrected.tsv").exists() + + @pytest.mark.parametrize("flag", ["--log-file", "--summary", "--json"]) + def test_dry_run_with_file_or_summary_option_is_an_error( + self, tmp_path: Path, flag: str + ) -> None: + """--dry-run with an option it would ignore exits with a usage error and writes nothing. + + Failure condition: the option is silently ignored and the run exits 0. + """ + from harmonizepy.__main__ import main + + data, desc = _small_inputs(tmp_path) + extra = [] if flag == "--json" else [str(tmp_path / "x.out")] + with pytest.raises(SystemExit) as excinfo: + main([data, desc, "--dry-run", flag, *extra]) + assert excinfo.value.code == 2 + assert not (tmp_path / "x.out").exists() + + def test_two_column_description_is_a_validation_error( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """A description with two columns gives an error message, not a traceback. + + Failure condition: an IndexError escapes from the batch lookup. + """ + from harmonizepy.__main__ import main + + data, desc = _small_inputs(tmp_path, "ID,grp\n" + "".join(f"s{i},1\n" for i in range(1, 7))) + with pytest.raises(SystemExit) as excinfo: + main([data, desc, "-q"]) + assert excinfo.value.code == 1 + assert "at least 3 columns" in capsys.readouterr().err + + +class TestCLIBatchCount: + """The batch count does not depend on the column order of the description.""" + + @pytest.mark.parametrize("order", list(_DESC_ORDERS)) + def test_summary_batch_count( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str], order: str + ) -> None: + """Every description column order gives two batches in the JSON summary. + + Failure condition: the summary counts the values of another column as batches. + """ + from harmonizepy.__main__ import main + + data, desc = _small_inputs(tmp_path, _DESC_ORDERS[order]) + main([data, desc, "--json", "-q"]) + assert json.loads(capsys.readouterr().out)["n_batches"] == 2 + + @pytest.mark.parametrize("order", list(_DESC_ORDERS)) + def test_dry_run_batch_count( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str], order: str + ) -> None: + """Every description column order gives two batches in the dry-run plan. + + Failure condition: the plan counts the values of another column as batches. + """ + from harmonizepy.__main__ import main + + data, desc = _small_inputs(tmp_path, _DESC_ORDERS[order]) + main([data, desc, "--dry-run"]) + assert re.search(r"Batches:\s+2\b", capsys.readouterr().out) + + +_PATTERN_DATA: str = ( + "id\ts1\ts2\ts3\ts4\ts5\ts6\n" + + "".join(f"p{i}\t{1.0 + i}\t{1.5 + i}\t{2.1 + i}\t{2.4 + i}\t\t\n" for i in range(1, 5)) + + "p5\t1.0\t1.4\t2.0\t2.6\t3.1\t3.5\n" +) +_PATTERN_DESC: str = "ID,sample,batch\n" + "".join( + f"s{i},{i},{(i + 1) // 2}\n" for i in range(1, 7) +) + + +class TestCLIDryRunMatchesRun: + """The dry run reports the groups the correction run uses.""" + + @pytest.mark.parametrize("extra", [[], ["--sort", "sparsity", "--block", "2"]]) + def test_submatrix_count_matches_correction_run( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str], extra: list[str] + ) -> None: + """The dry-run sub-matrix count equals the number of groups the run corrects. + + p5 is the only feature seen in all three batches, so unique removal moves it + into the pattern of p1 to p4 and the run corrects one group. + + Failure condition: the dry run skips unique removal or sorting and reports a + different count. + """ + data = tmp_path / "data.tsv" + data.write_text(_PATTERN_DATA, encoding="utf-8") + desc = tmp_path / "desc.csv" + desc.write_text(_PATTERN_DESC, encoding="utf-8") + + main([str(data), str(desc), "--dry-run", *extra]) + planned = re.search(r"Sub-matrices:\s+(\d+)", capsys.readouterr().out) + main([str(data), str(desc), "--no-log", *extra]) + corrected = re.search(r"Adjusting (\d+) unique affiliation group", capsys.readouterr().err) + assert planned is not None and corrected is not None + assert planned.group(1) == corrected.group(1) == "1" + + +class TestCLIRepeatedCalls: + """Several runs in one process.""" + + def test_second_run_logs_each_line_once( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """A second ``main()`` call prints each log line once. + + Failure condition: the first call's handlers stay attached, and every line of + the second call appears twice. + """ + data, desc = _small_inputs(tmp_path) + main([data, desc, "--no-log"]) + capsys.readouterr() + main([data, desc, "--no-log"]) + lines = capsys.readouterr().err.splitlines() + done = [line for line in lines if "Done (" in line] + assert len(done) == 1 + + +class TestCLISummaryValues: + """Values recorded in the run summary.""" + + def test_summary_records_resolved_needed_values( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """Without --needed-values, the summary records the value the run used. + + Failure condition: the summary records null for an automatic value. + """ + data, desc = _small_inputs(tmp_path) + main([data, desc, "--json", "-q", "--combat-mode", "2"]) + assert json.loads(capsys.readouterr().out)["needed_values"] == 1 + + +class TestCLIConfigErrors: + """Unreadable config files end with a usage error, not a traceback.""" + + def test_malformed_yaml_is_a_usage_error( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + """A YAML config that does not parse exits with code 2 and a message. + + Failure condition: the YAML parser's exception escapes as a traceback. + """ + pytest.importorskip("yaml") + data, desc = _small_inputs(tmp_path) + config = tmp_path / "run.yaml" + config.write_text("algorithm: [unclosed\n", encoding="utf-8") + with pytest.raises(SystemExit) as excinfo: + main([data, desc, "--config", str(config)]) + assert excinfo.value.code == 2 + assert "invalid YAML" in capsys.readouterr().err + + +def test_main_restores_package_logger_settings(tmp_path: Path) -> None: + """After ``main()`` returns, the package logger has its earlier level and propagation. + + Failure condition: the logger stays at DEBUG without propagation, so later + library calls in the same process lose records from root handlers. + """ + import logging + + package_logger = logging.getLogger("harmonizepy") + before = (package_logger.level, package_logger.propagate) + data, desc = _small_inputs(tmp_path) + main([data, desc, "--no-log", "-q"]) + assert (package_logger.level, package_logger.propagate) == before + + +def test_dry_run_reports_untransformed_input( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + """The dry run shows the input-scale warning on stderr for raw intensities. + + Failure condition: the dry run validates raw intensities without a word. + """ + rng = np.random.default_rng(31) + samples = [f"s{i}" for i in range(1, 7)] + data = pd.DataFrame( + rng.lognormal(12, 1, (20, 6)), index=[f"p{i}" for i in range(20)], columns=samples + ) + data_path = tmp_path / "raw.tsv" + data.to_csv(data_path, sep="\t") + desc_path = tmp_path / "desc.csv" + pd.DataFrame({"ID": samples, "sample": range(1, 7), "batch": [1, 1, 1, 2, 2, 2]}).to_csv( + desc_path, index=False + ) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + main([str(data_path), str(desc_path), "--dry-run"]) + assert any("look untransformed" in str(w.message) for w in caught) + + +class TestCLIOutputSafety: + """No output file may overwrite an input or another output, and config values are checked.""" + + @pytest.mark.parametrize("flag", ["-o", "--summary", "--log-file", "--report"]) + def test_output_naming_the_data_file_is_refused(self, tmp_path: Path, flag: str) -> None: + """Any output named like the data file is a usage error, and the file is untouched. + + Failure condition: ``-o`` or ``--summary`` overwrites the data file, or + ``--log-file`` truncates it before it is read. + """ + data, desc = _small_inputs(tmp_path) + before = Path(data).read_bytes() + argv = [data, desc, "-q", flag, data] + if flag != "-o": + argv += ["-o", str(tmp_path / "out.tsv")] + with pytest.raises(SystemExit) as excinfo: + main(argv) + assert excinfo.value.code == 2 + assert Path(data).read_bytes() == before + + def test_two_outputs_naming_one_file_are_refused(self, tmp_path: Path) -> None: + """The summary and the report cannot be the same file. + + Failure condition: the report silently replaces the summary. + """ + data, desc = _small_inputs(tmp_path) + same = str(tmp_path / "same.json") + with pytest.raises(SystemExit) as excinfo: + main([data, desc, "--no-log", "-q", "--summary", same, "--report", same]) + assert excinfo.value.code == 2 + + @pytest.mark.parametrize( + ("key", "value"), + [ + ("output_format", "xlsx"), + ("combat_mode", 9), + ("needed_values", 2.5), + ("unique_removal", "no"), + ("block", True), + ], + ) + def test_invalid_config_value_is_a_usage_error( + self, tmp_path: Path, key: str, value: object + ) -> None: + """A config value the matching flag would reject exits with code 2. + + Failure condition: ``output_format: xlsx`` writes TSV and exits 0, or a bad + mode exits 1 after reading the inputs. + """ + data, desc = _small_inputs(tmp_path) + config = tmp_path / "run.json" + config.write_text(json.dumps({key: value}), encoding="utf-8") + with pytest.raises(SystemExit) as excinfo: + main([data, desc, "--no-log", "-q", "--config", str(config)]) + assert excinfo.value.code == 2 + + def test_dry_run_refuses_a_flag_that_repeats_the_config(self, tmp_path: Path) -> None: + """``--summary`` typed on the command line conflicts with a dry run even when + the config file holds the same value. + + Failure condition: the flag is accepted because its value equals the config's. + """ + data, desc = _small_inputs(tmp_path) + summary = str(tmp_path / "s.json") + config = tmp_path / "run.json" + config.write_text(json.dumps({"summary": summary}), encoding="utf-8") + with pytest.raises(SystemExit) as excinfo: + main([data, desc, "--dry-run", "--config", str(config), "--summary", summary]) + assert excinfo.value.code == 2 diff --git a/tests/test_combat.py b/tests/test_combat.py index 21b6605..7eda732 100644 --- a/tests/test_combat.py +++ b/tests/test_combat.py @@ -12,6 +12,8 @@ from __future__ import annotations +import logging +import warnings from pathlib import Path import numpy as np @@ -20,11 +22,11 @@ from harmonizepy.combat import ( _beta_na_grouped_batch_design, - _group_valid_rows, _int_eprior, _it_sol, _row_var_nan_grouped, combat, + group_valid_rows, ) from harmonizepy.combat_wrapper import adjust_combat @@ -64,7 +66,7 @@ def _int_eprior_reference( g_hat: np.ndarray, d_hat: np.ndarray, ) -> tuple[np.ndarray, np.ndarray]: - """Reference implementation matching the pre-optimization broadcast formula.""" + """Per-block reference for ``_int_eprior``: the expanded likelihood, with broadcasting.""" n_genes, _ = s_data.shape g_star = np.empty(n_genes) d_star = np.empty(n_genes) @@ -153,7 +155,7 @@ def _it_sol_reference( conv: float = 1e-4, max_iter: int = 1_000_000, ) -> tuple[np.ndarray, np.ndarray]: - """Reference `_it_sol` using the pre-optimization iteration structure.""" + """Reference ``_it_sol``: one batch, a fresh array per iteration.""" nan_mask = np.isnan(s_data) all_nan = nan_mask.all(axis=1) active = ~all_nan @@ -279,7 +281,7 @@ def test_it_sol_all_nan_short_circuits_without_warning(self, caplog: pytest.LogC assert "did not converge" not in caplog.text def test_it_sol_matches_reference_on_finite_nan_mixture(self): - """Optimized `_it_sol` must match the pre-optimization iteration math. + """``_it_sol`` matches the one-batch reference on data with missing cells. Failure condition: buffer reuse or in-place updates change the fixed point reached by the parametric EB solver on mixed-observation data. @@ -319,10 +321,10 @@ def test_it_sol_matches_reference_on_finite_nan_mixture(self): np.testing.assert_allclose(result_d, expected_d, rtol=1e-12, atol=1e-12, equal_nan=True) def test_int_eprior_matches_reference_formula(self): - """Optimized `_int_eprior` must match the broadcast reference math. + """``_int_eprior`` matches the broadcast reference on ordinary data. - Failure condition: the binomial-form optimization changes the - posterior estimates relative to the original likelihood formula. + Failure condition: the block computation changes the posterior estimates + relative to the reference likelihood. Tolerances: rtol=1e-12/atol=1e-12 because both implementations evaluate the same formula in float64 with only algebraic @@ -390,7 +392,7 @@ def test_row_var_nan_grouped_reuses_shared_valid_row_groups(self): dtype=np.float64, ) - valid_row_groups = _group_valid_rows(data) + valid_row_groups = group_valid_rows(data) expected_var = _row_var_nan_grouped_reference(data) result_var = _row_var_nan_grouped(data, valid_row_groups) @@ -421,7 +423,7 @@ def test_beta_na_grouped_batch_design_matches_lstsq_reference(self): dtype=np.float64, ) - valid_row_groups = _group_valid_rows(data) + valid_row_groups = group_valid_rows(data) expected = _beta_na_grouped_reference(data, design) result = _beta_na_grouped_batch_design(data, design, valid_row_groups) @@ -614,9 +616,9 @@ def test_sva_combat(self, mode, par_prior, mean_only): Failure condition: the Python implementation diverges from R reference beyond documented tolerances. - Tolerances: rtol=1e-4/atol=1e-6 for parametric iterative - modes (1, 3); closed-form modes are tighter but this - tolerance covers all modes. + Tolerances: rtol=1e-4/atol=1e-6 for mode 1, whose parametric + solver iterates to a 1e-4 convergence threshold; the other modes + agree more closely, but this tolerance covers all modes. """ expected = _load_fixture(f"small_combat_mode{mode}.tsv") result = combat(self.data, self.batches, par_prior=par_prior, mean_only=mean_only) @@ -627,3 +629,710 @@ def test_sva_combat(self, mode, par_prior, mean_only): atol=1e-6, err_msg=f"Mismatch vs R sva::ComBat mode {mode}", ) + + +class TestFeaturesLeftRaw: + """Features the shared prior cannot use keep their raw values and change nothing else. + + A constant feature has zero variance inside each batch. If it entered the + empirical-Bayes prior, it would switch shrinkage off for every feature (#18). + """ + + @staticmethod + def _matrix(n_features: int = 500) -> tuple[np.ndarray, np.ndarray]: + rng = np.random.default_rng(1) + batch = np.array([0] * 6 + [1] * 6) + data = ( + rng.normal(20, 2, (n_features, 1)) + + rng.normal(0, 0.3, (n_features, 12)) + + rng.normal(1, 0.5, (n_features, 1)) * (batch == 1) + ) + return data, batch + + # A constant, a constant that is not an exact binary fraction, and a constant + # with one-ulp noise, whose variance is far below the floor but not zero. + @pytest.mark.parametrize( + "low, high", [(18.0, 19.0), (0.1, 0.7), (0.1, float(np.nextafter(0.1, 1.0)))] + ) + @pytest.mark.parametrize("mean_only", [False, True]) + def test_constant_row_left_raw_and_others_unchanged( + self, low: float, high: float, mean_only: bool + ) -> None: + """A constant row keeps its values, and every other row is as if it were absent. + + Failure condition: the constant row enters the prior and changes the other + rows, or is itself corrected. + """ + data, batch = self._matrix() + constant = np.array([[low] * 6 + [high] * 6]) + alone = combat(data, batch, mean_only=mean_only) + out = combat(np.vstack([data, constant]), batch, mean_only=mean_only) + # Exact equality: the other rows go through the same computation as without + # the constant row. + np.testing.assert_array_equal(out[:500], alone) + np.testing.assert_array_equal(out[500], constant[0]) + + @pytest.mark.parametrize("mean_only", [False, True]) + def test_non_parametric_constant_row_left_raw_and_others_unchanged( + self, mean_only: bool + ) -> None: + """In modes 3 and 4, a row constant in every batch keeps its values. + + Failure condition: the row, whose values cannot be standardised, is given a + shift that does not come from its data, or changes the other rows. + """ + data, batch = self._matrix(60) + constant = np.array([[19.0] * 6 + [21.0] * 6]) + alone = combat(data, batch, par_prior=False, mean_only=mean_only) + out = combat(np.vstack([data, constant]), batch, par_prior=False, mean_only=mean_only) + np.testing.assert_array_equal(out[:60], alone) + np.testing.assert_array_equal(out[60], constant[0]) + + def test_non_parametric_row_constant_in_one_batch_is_corrected(self) -> None: + """In mode 3, a row constant in one batch only has its batch shift removed. + + Failure condition: the row is left raw and keeps a batch shift of 2. + """ + data, batch = self._matrix(60) + row = np.array([[18.0] * 6 + [20.1, 19.7, 20.3, 19.9, 20.2, 19.8]]) + out = combat(np.vstack([data, row]), batch, par_prior=False)[60] + assert np.isfinite(out).all() + assert abs(out[6:].mean() - out[:6].mean()) < 1.0 + + def test_constant_row_with_missing_cells(self) -> None: + """The missing-value path leaves a constant row raw and the others unchanged. + + Failure condition: the constant row, observed in four samples per batch, + enters the prior on the missing-value path. + """ + data, batch = self._matrix() + data[0, 0] = np.nan + constant = np.array([[0.1] * 6 + [0.7] * 6]) + constant[0, [0, 6]] = np.nan + alone = combat(data, batch) + out = combat(np.vstack([data, constant]), batch) + np.testing.assert_array_equal(out[:500], alone) + np.testing.assert_array_equal(out[500], constant[0]) + + def test_constant_reference_batch_left_raw(self) -> None: + """A row constant in the reference batch alone is left raw in mean-only mode. + + Failure condition: the row's pooled variance, taken from the reference batch, + is zero and the row enters the prior. + """ + data, batch = self._matrix() + row = np.array([[5.0] * 6 + [4.0, 6.0, 5.0, 4.5, 5.5, 5.2]]) + alone = combat(data, batch, mean_only=True, ref_batch=0) + out = combat(np.vstack([data, row]), batch, mean_only=True, ref_batch=0) + np.testing.assert_array_equal(out[:500], alone) + np.testing.assert_array_equal(out[500], row[0]) + + def test_single_sample_batch_constant_elsewhere_is_corrected(self) -> None: + """With a one-sample batch, a batch with constant values does not block correction. + + A one-sample batch forces location-only correction, which never divides by a + batch's variance, so only a zero pooled variance makes a row unestimable. + + Failure condition: the row is left raw although the engine corrects it. + """ + rng = np.random.default_rng(2) + batch = np.array([0, 0, 0, 1, 2, 2]) + data = rng.normal(5, 1, (20, 6)) + row = np.array([[5.0, 5.0, 5.0, 6.0, 1.0, 2.0]]) + out = combat(np.vstack([data, row]), batch) + assert not np.array_equal(out[20], row[0]) + assert np.isfinite(out[20]).all() + + def test_sparse_row_with_spread_is_corrected(self) -> None: + """A sparse row with spread in two batches and none elsewhere is corrected. + + Failure condition: the row is left raw because it has few observations, + although its variance is positive. + """ + rng = np.random.default_rng(3) + batch = np.repeat([0, 1, 2, 3], 2) + data = rng.normal(5, 1, (30, 8)) + row = np.array([[1.0, 5.0, np.nan, np.nan, 2.0, 6.0, np.nan, np.nan]]) + out = combat(np.vstack([data, row]), batch) + observed = ~np.isnan(row[0]) + assert not np.array_equal(out[30, observed], row[0, observed]) + assert np.isfinite(out[30, observed]).all() + + def test_unknown_ref_batch_raises_when_every_row_is_constant(self) -> None: + """An unknown reference batch is rejected before any row is left raw. + + Failure condition: the call returns the raw matrix without an error. + """ + batch = np.array([0] * 6 + [1] * 6) + data = np.repeat([[1.0] * 6 + [2.0] * 6], 3, axis=0) + with pytest.raises(ValueError, match="ref_batch=99"): + combat(data, batch, ref_batch=99) + + @pytest.mark.parametrize( + "row", + [ + pytest.param([3.0 + 1e-9 * k for k in range(12)], id="spread-1e-9"), + pytest.param([1e-200 * (1.0 + 0.1 * (k % 10)) for k in range(12)], id="underflow"), + ], + ) + def test_row_below_the_variance_floor_left_raw(self, row: list[float]) -> None: + """A row whose pooled variance is below the 1e-12 floor keeps its values. + + Failure condition: the engine floors the variance and returns values that do + not come from the row, or the row changes the other rows. + """ + data, batch = self._matrix() + alone = combat(data, batch) + out = combat(np.vstack([data, row]), batch) + np.testing.assert_array_equal(out[:500], alone) + np.testing.assert_array_equal(out[500], row) + + def test_feature_in_a_single_batch_is_left_raw( + self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A feature with values in one batch only keeps them, and the log counts it. + + Failure condition: the feature is rescaled although it has no batch effect + to estimate. + """ + # The command line turns off propagation on the package logger, and caplog + # only sees records that propagate to the root logger. + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + data, batch = self._matrix(50) + row = np.array([[7.0, 8.0, 7.5] + [np.nan] * 9]) + with caplog.at_level(logging.INFO, logger="harmonizepy.combat"): + out = combat(np.vstack([data, row]), batch) + np.testing.assert_array_equal(out[50], row[0]) + assert "1 feature(s) with values in a single batch left uncorrected" in caplog.text + + def test_single_reference_value_mean_only_is_corrected(self) -> None: + """In mean-only mode, one reference value and a constant batch are still corrected. + + Failure condition: the row is left raw although the engine estimates it. + """ + data, batch = self._matrix(50) + row = np.array([[7.0] + [np.nan] * 5 + [3.0] * 6]) + out = combat(np.vstack([data, row]), batch, mean_only=True, ref_batch=0) + assert np.isfinite(out[50, 6:]).all() + assert not np.array_equal(out[50, 6:], row[0, 6:]) + + def test_flag_matches_the_engine_floor_on_sparse_rows(self) -> None: + """On random sparse rows, a row is left raw exactly when its pooled variance is floored. + + The pooled variance is recomputed here from its definition: the sample variance + of the residuals from the batch means over observed cells, 1.0 with at most one + observed value. + + Failure condition: the flag and the engine disagree for some row. + """ + from harmonizepy.combat import _VARIANCE_FLOOR, _unestimable_rows + + rng = np.random.default_rng(6) + batch = np.repeat([0, 1, 2], 3) + data = rng.choice([1.0, 2.0, np.nan], size=(400, 9), p=[0.4, 0.2, 0.4]) + flags = _unestimable_rows(data, batch, mean_only=True, ref_batch=None) + for row, flagged in zip(data, flags, strict=True): + means = { + b: np.nanmean(row[batch == b]) + for b in range(3) + if (~np.isnan(row[batch == b])).any() + } + resid = np.array( + [v - means[b] for v, b in zip(row, batch, strict=True) if not np.isnan(v)] + ) + var = 1.0 if resid.size <= 1 else float(resid @ resid) / (resid.size - 1) + assert flagged == (var < _VARIANCE_FLOOR) + + def test_infinite_values_rejected(self) -> None: + """An infinite value, as log2 of zero gives, is rejected with the feature named. + + Failure condition: the solver runs on the infinite row and every output value + becomes missing. + """ + data, batch = self._matrix(50) + data[3, 0] = -np.inf + with pytest.raises( + ValueError, match=r"infinite values in 1 feature\(s\) \(first: \['3'\]\)" + ): + combat(data, batch) + + def test_single_sample_reference_batch_rejected(self) -> None: + """A reference batch with one sample is rejected, since it has no variance to pool. + + Failure condition: every row's pooled variance is zero and the output depends + on whether the data has a missing cell. + """ + rng = np.random.default_rng(7) + batch = np.array([0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]) + with pytest.raises(ValueError, match="single sample"): + combat(rng.normal(10, 1, (20, 12)), batch, mean_only=True, ref_batch=0) + + def test_one_row_input_returned_raw(self) -> None: + """A single feature is returned raw, including a row with a missing cell. + + Failure condition: the solver runs on one row and returns missing values. + """ + row = np.array([[1.0, np.nan, 3.0, 4.0, 5.0, 6.0]]) + out = combat(row, np.array([0, 0, 0, 1, 1, 1])) + np.testing.assert_array_equal(out, row) + + +def test_solver_stops_on_a_non_finite_change( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """The empirical-Bayes solver stops at the first iteration when its change is not finite. + + Failure condition: the loop runs to its iteration limit, which by default takes + about a minute, on a missing scale estimate. + """ + # The command line turns off propagation on the package logger, and caplog + # only sees records that propagate to the root logger. + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + s_data = np.array([[0.1, -0.2, 0.3], [0.2, 0.1, -0.1]]) + d_hat = np.array([np.nan, 1.0]) + with caplog.at_level(logging.WARNING, logger="harmonizepy.combat"): + _, delta = _it_sol(s_data, np.zeros(2), d_hat, 0.0, 1.0, 2.0, 1.0) + assert np.isnan(delta[0]) + assert "stopped at iteration 1" in caplog.text + + +class TestEngineInputs: + """Inputs that the engines must reject or set aside before fitting.""" + + def test_feature_without_values_leaves_others_unchanged(self) -> None: + """A feature with no observed value stays missing and does not change the others. + + Failure condition: the missing feature enters the prior, and every output + value becomes missing. + """ + rng = np.random.default_rng(8) + batch = np.repeat([0, 1], 6) + data = rng.normal(10, 1, (20, 12)) + np.repeat([0.0, 1.0], 6) + with_empty = np.vstack([data, np.full((1, 12), np.nan)]) + out = combat(with_empty, batch) + np.testing.assert_array_equal(out[:20], combat(data, batch)) + assert np.isnan(out[20]).all() + + @pytest.mark.parametrize( + "labels", + [ + [0.2, 0.2, 0.9, 0.9], + [0, 0, np.nan, 1], + ["a", "a", "b", "b"], + [1 + 2j, 1 + 2j, 2, 2], + [1e16, 1e16, 2e16, 2e16], + ], + ) + def test_labels_that_are_not_whole_numbers_raise(self, labels: list[object]) -> None: + """Fractional, missing, or text batch labels are rejected. + + Failure condition: 0.2 and 0.9 are cast to the same integer and treated as + one batch, so nothing is corrected; a complex label loses its imaginary part; + a float too large to be exact is rounded to a neighbouring batch. + """ + data = np.random.default_rng(9).normal(size=(5, 4)) + with pytest.raises(ValueError, match=r"batch labels must be whole numbers below 2\*\*53"): + combat(data, labels) + + def test_whole_float_labels_match_integer_labels(self) -> None: + """Labels written as 0.0 and 1.0 give the same result as 0 and 1. + + Failure condition: whole numbers stored as floats are rejected or mapped + differently. + """ + data = np.random.default_rng(10).normal(size=(10, 6)) + np.testing.assert_array_equal( + combat(data, [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]), combat(data, [0, 0, 0, 1, 1, 1]) + ) + + def test_error_lists_each_offending_label_once(self) -> None: + """The error names each offending label once, quoted. + + Failure condition: the message repeats one label per sample. + """ + data = np.random.default_rng(14).normal(size=(5, 4)) + with pytest.raises(ValueError, match=r"found 0\.2, 0\.9\.$"): + combat(data, [0.2, 0.2, 0.9, 0.9]) + + @pytest.mark.parametrize("ref_batch", [None, 0]) + @pytest.mark.parametrize("n_live", [1, 20]) + def test_features_without_values_with_reference_and_few_rows( + self, ref_batch: int | None, n_live: int + ) -> None: + """Features without values stay missing with a reference batch and with one live row. + + Failure condition: the set-aside breaks the reference batch or the single + feature rule, or an unestimable row next to it. + """ + rng = np.random.default_rng(15) + batch = np.repeat([0, 1], 6) + live = rng.normal(10, 1, (n_live, 12)) + np.repeat([0.0, 1.0], 6) + constant = np.array([[5.0] * 6 + [6.0] * 6]) + empty = np.full((2, 12), np.nan) + out = combat(np.vstack([live, constant, empty]), batch, ref_batch=ref_batch) + np.testing.assert_array_equal(out[:n_live], combat(live, batch, ref_batch=ref_batch)) + np.testing.assert_array_equal(out[n_live], constant[0]) + assert np.isnan(out[n_live + 1 :]).all() + + def test_every_feature_without_values_returns_a_copy(self) -> None: + """A matrix with no observed value is returned unchanged. + + Failure condition: the set-aside recurses on an empty matrix or raises. + """ + empty = np.full((3, 4), np.nan) + assert np.isnan(combat(empty, [0, 0, 1, 1])).all() + + def test_adjust_combat_checks_batch_length_first(self) -> None: + """``adjust_combat`` rejects a batch of the wrong length even with one batch label. + + Failure condition: the single-batch shortcut returns a copy without the check. + """ + frame = pd.DataFrame(np.ones((3, 4)), columns=list("abcd")) + with pytest.raises(ValueError, match="batch length"): + adjust_combat(frame, [0, 0]) + + +def _reference_it_sol( + s_data: np.ndarray, + g_hat: np.ndarray, + d_hat: np.ndarray, + g_bar: float, + t2: float, + a: float, + b: float, +) -> tuple[np.ndarray, np.ndarray]: + """One-batch solver written after R ``sva::it.sol`` 3.60.0, as a per-batch oracle. + + Each feature uses its observed cells; the change is ``max(change_g, change_d)`` + with Python's ``max``, so a NaN scale change is ignored while the location + change is finite; the loop stops at a non-finite change or below 1e-4. + """ + n = np.maximum((~np.isnan(s_data)).sum(axis=1).astype(float), 1.0) + sum_x, sum_x2 = np.nansum(s_data, axis=1), np.nansum(s_data * s_data, axis=1) + g_prev, d_prev = g_hat.copy(), d_hat.copy() + while True: + g = (t2 * n * g_hat + d_prev * g_bar) / (t2 * n + d_prev) + d = (0.5 * (g * g * n - 2.0 * g * sum_x + sum_x2) + b) / (0.5 * n + a - 1.0) + change = max( + float((np.abs(g - g_prev) / np.maximum(np.abs(g_prev), 1e-12)).max()), + float((np.abs(d - d_prev) / np.maximum(np.abs(d_prev), 1e-12)).max()), + ) + if not np.isfinite(change) or change < 1e-4: + return g, d + g_prev, d_prev = g, d + + +class TestBatchedSolver: + """The empirical-Bayes solver that iterates all batches of a group together.""" + + # The setup takes the mean of a row with no observed cell in one batch. + @pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning") + @pytest.mark.filterwarnings("ignore:Degrees of freedom:RuntimeWarning") + def test_batched_solver_equals_one_batch_at_a_time(self) -> None: + """Solving all batches together gives exactly the per-batch results. + + Batches converge after different numbers of iterations, and one row has no + observed cell in a batch, so per-batch stopping and inactive rows are both + exercised. + + Failure condition: a batch keeps iterating after its own convergence, or an + inactive row is updated. + """ + from harmonizepy.combat import _it_sol_batches + + rng = np.random.default_rng(16) + batches_ind = [np.arange(0, 4), np.arange(4, 10), np.arange(10, 13)] + s_data = rng.normal(0, 1, (40, 13)) * np.repeat([0.5, 1.0, 3.0], [4, 6, 3]) + s_data[3, 4:10] = np.nan + s_data[rng.random(s_data.shape) < 0.1] = np.nan + g_hat = np.array([np.nanmean(s_data[:, idx], axis=1) for idx in batches_ind]) + d_hat = np.array([np.nanvar(s_data[:, idx], axis=1, ddof=1) for idx in batches_ind]) + g_hat = np.nan_to_num(g_hat) + d_hat = np.nan_to_num(d_hat, nan=1.0) + g_bar, t2 = g_hat.mean(axis=1), g_hat.var(axis=1, ddof=1) + a, b = np.array([2.0, 3.0, 5.0]), np.array([1.0, 2.0, 4.0]) + together = _it_sol_batches(s_data, batches_ind, g_hat, d_hat, g_bar, t2, a, b) + for i, idx in enumerate(batches_ind): + alone = _it_sol(s_data[:, idx], g_hat[i], d_hat[i], g_bar[i], t2[i], a[i], b[i]) + np.testing.assert_array_equal(together[0][i], alone[0]) + np.testing.assert_array_equal(together[1][i], alone[1]) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + @pytest.mark.parametrize("scale", [1.0, 1e250]) + def test_matches_the_per_batch_reference(self, scale: float) -> None: + """The solver equals the R-style one-batch reference, for ordinary and huge values. + + Failure condition: the batched loop's stopping rule or arithmetic departs from + the one-batch reference. + """ + rng = np.random.default_rng(19) + for _ in range(20): + s_data = rng.normal(0, 1, (1, 2)) * scale + g_hat = s_data.mean(axis=1) + d_hat = np.maximum(s_data.var(axis=1, ddof=1), 1e-12) + expected = _reference_it_sol(s_data, g_hat, d_hat, 0.0, 1.0, 3.0, 2.0) + got = _it_sol(s_data, g_hat, d_hat, 0.0, 1.0, 3.0, 2.0) + np.testing.assert_array_equal(got[0], expected[0]) + np.testing.assert_array_equal(got[1], expected[1]) + + @pytest.mark.filterwarnings("ignore::RuntimeWarning") + def test_warnings_follow_batch_order( + self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Warnings for several batches appear in batch order, with the final change. + + Failure condition: the warnings follow the iteration at which each batch + stopped, or the non-convergence warning lacks the final change. + """ + from harmonizepy.combat import _it_sol_batches + + # The command line turns off propagation on the package logger, and caplog + # only sees records that propagate to the root logger. + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + rng = np.random.default_rng(20) + s_data = np.hstack([rng.normal(0, 1, (5, 4)), rng.normal(0, 1, (5, 4)) * 1e200]) + batches_ind = [np.arange(4), np.arange(4, 8)] + g_hat = np.array([s_data[:, idx].mean(axis=1) for idx in batches_ind]) + d_hat = np.array([s_data[:, idx].var(axis=1, ddof=1) for idx in batches_ind]) + with caplog.at_level(logging.WARNING, logger="harmonizepy.combat"): + _it_sol_batches( + s_data, + batches_ind, + g_hat, + d_hat, + np.zeros(2), + np.ones(2), + np.full(2, 3.0), + np.full(2, 2.0), + max_iter=2, + ) + messages = [record.getMessage() for record in caplog.records] + assert messages[0].startswith("Batch did not converge after 2 iterations (final change=") + assert "not finite" in messages[1] + + +class TestDesignCache: + """The design cache stays within its bounds and keeps repeated layouts.""" + + def test_design_cache_stays_within_its_byte_bound(self) -> None: + """Wide designs do not keep the cache above its byte bound after a call. + + Failure condition: the cache keeps every design of a wide run alive. + """ + from harmonizepy.combat import _DESIGN_CACHE_MAX_BYTES, _design_cache_bytes + + rng = np.random.default_rng(17) + n_samples = 20_000 + for n_batch in range(2, 40): + batch = np.arange(n_samples) % n_batch + combat(rng.normal(size=(3, n_samples)), batch, mean_only=True) + assert _design_cache_bytes() <= _DESIGN_CACHE_MAX_BYTES + + def test_recent_layout_stays_cached_when_the_budget_is_full(self) -> None: + """After the byte budget is reached, the newest layouts remain cached. + + Failure condition: the whole cache is cleared, so a layout used again at + once must be rebuilt. + """ + from harmonizepy.combat import _design_cache, _get_cached_design + + n_samples = 20_000 + for n_batch in range(2, 40): + _get_cached_design(np.arange(n_samples) % n_batch, n_batch) + last = np.arange(n_samples) % 39 + assert (39, last.astype(np.intp).tobytes()) in _design_cache + + +class TestNonParametricPrior: + """The likelihood-weighted prior of the non-parametric modes.""" + + def test_missing_likelihood_falls_back_to_equal_weights(self) -> None: + """When a support feature's scale is NaN, the other targets average the rest equally. + + The feature with the NaN scale is left out of its own average, so its row has + no NaN and is weighted by likelihood as usual. + + Failure condition: the NaN spreads into the location estimates, or a target + keeps its own estimate in the average. + """ + rng = np.random.default_rng(21) + s_data = rng.normal(0, 1, (6, 5)) + g_hat = s_data.mean(axis=1) + d_hat = s_data.var(axis=1, ddof=1) + d_hat[0] = np.nan + g_star, _ = _int_eprior(s_data, g_hat, d_hat) + expected = np.array([np.delete(g_hat, i).mean() for i in range(1, 6)]) + # Equal weights sum the same five values in another order than np.mean. + np.testing.assert_allclose(g_star[1:], expected, rtol=1e-14) + assert np.isfinite(g_star[0]) + + def test_far_targets_do_not_underflow(self) -> None: + """Targets far from every support feature still get finite estimates. + + Failure condition: all weights underflow to zero and the estimate is NaN. + """ + rng = np.random.default_rng(22) + s_data = rng.normal(0, 1, (50, 6)) + s_data[0] += 1e3 + g_hat = s_data.mean(axis=1) + d_hat = s_data.var(axis=1, ddof=1) + g_star, d_star = _int_eprior(s_data, g_hat, d_hat) + assert np.isfinite(g_star).all() and np.isfinite(d_star).all() + + +def _reference_int_eprior( + s_data: np.ndarray, g_hat: np.ndarray, d_hat: np.ndarray +) -> tuple[np.ndarray, np.ndarray]: + """Per-pair loop written after R ``sva:::int.eprior`` 3.60.0, as an oracle. + + The likelihood of target i under feature j sums the squared residuals + ``(x - g_j)^2`` directly, as R does, so it keeps full precision when the + values lie far from ``g_j``. Weights are scaled by the row maximum before + ``exp`` (R works in direct space and underflows earlier). + """ + g_star, d_star = g_hat.copy(), d_hat.copy() + for i in range(s_data.shape[0]): + x = s_data[i][~np.isnan(s_data[i])] + others = [j for j in range(s_data.shape[0]) if j != i] + ll = np.array( + [ + -((x - g_hat[j]) ** 2).sum() / (2 * d_hat[j]) + - x.size / 2 * np.log(2 * np.pi * d_hat[j]) + for j in others + ] + ) + w = np.exp(ll - ll.max()) + g_star[i] = (w * g_hat[others]).sum() / w.sum() + d_star[i] = (w * d_hat[others]).sum() / w.sum() + return g_star, d_star + + +@pytest.mark.parametrize("centre", [0.0, 1e4, 1e6]) +def test_non_parametric_prior_keeps_precision_far_from_the_estimates(centre: float) -> None: + """Targets far from the support estimates, relative to their spread, keep full precision. + + Failure condition: the likelihood is formed from sums of ``x^2`` and ``x``, + whose difference cancels, so the scale estimates go wrong by up to a factor of + three at a centre of 1e6 with a spread of 1e-3. + """ + rng = np.random.default_rng(23) + s_data = centre + rng.normal(0, 1e-3, (50, 6)) + rng.normal(0, 1e-2, (50, 1)) + g_hat = s_data.mean(axis=1) + rng.normal(0, 1e-3, 50) + d_hat = s_data.var(axis=1, ddof=1) + g_star, d_star = _int_eprior(s_data, g_hat, d_hat) + g_ref, d_ref = _reference_int_eprior(s_data, g_hat, d_hat) + # The reference itself carries rounding of order eps * centre^2 / d in the + # exponent; 1e-6 relative separates that from the cancellation it guards. + np.testing.assert_allclose(g_star, g_ref, rtol=1e-6) + np.testing.assert_allclose(d_star, d_ref, rtol=1e-6) + + +class TestUnobservedBatch: + """A feature with no value in a whole batch is fitted on the batches it has.""" + + @staticmethod + def _data() -> tuple[np.ndarray, np.ndarray]: + rng = np.random.default_rng(24) + batch = np.repeat([0, 1, 2], 4) + shift = np.array([0.0, 1.0, -1.0])[batch] + data = rng.normal(10, 0.3, (200, 12)) + rng.normal(0, 0.5, (200, 1)) + shift + data[0, batch == 2] = np.nan + data[0, batch < 2] = 10.0 + shift[batch < 2] + rng.normal(0, 0.3, 8) + return data, batch + + @pytest.mark.parametrize( + "kwargs", + [{}, {"mean_only": True}, {"par_prior": False}, {"par_prior": False, "mean_only": True}], + ) + def test_level_follows_the_observed_batches(self, kwargs: dict[str, bool]) -> None: + """The feature's level stays near its correction on the observed batches alone. + + Counting the unobserved batch as a batch effect of zero would pull a level of + about 10.4 down to about 7.2. What remains is the shrinkage towards batch + priors centred on the all-batch mean. + + Failure condition: the unobserved batch enters the grand mean or the prior. + """ + data, batch = self._data() + keep = batch < 2 + level = np.nanmean(combat(data, batch, **kwargs)[0]) + alone = np.nanmean(combat(data[:, keep], batch[keep], **kwargs)[0]) + # The batch shifts are +-1 and the zero-effect bias would be 3.2; 0.4 covers the prior + # offset between the two fits, which reaches 0.25 in location-only mode. + assert abs(level - alone) < 0.4 + + def test_feature_missing_the_reference_batch_is_left_raw( + self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch + ) -> None: + """With ``ref_batch``, a feature with no value in the reference keeps its values. + + Failure condition: the feature is adjusted to a reference level it does not + have, which pulled its level towards zero. + """ + # The command line turns off propagation on the package logger, and caplog + # only sees records that propagate to the root logger. + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + data, batch = self._data() + with caplog.at_level(logging.INFO, logger="harmonizepy.combat"): + out = combat(data, batch, ref_batch=2) + np.testing.assert_array_equal(out[0], data[0]) + assert "1 feature(s) with no value in the reference batch left uncorrected" in caplog.text + + +def test_batch_observed_by_one_feature_gives_finite_output() -> None: + """A batch in which only one feature has values leaves every output finite. + + That batch has no prior to estimate, so its estimates are used unshrunk. + + Failure condition: the prior variance of the batch is undefined and turns the + complete feature's values in that batch into NaN. + """ + rng = np.random.default_rng(32) + batch = np.repeat([0, 1, 2], 4) + data = rng.normal(10, 1, (3, 12)) + np.repeat([0.0, 1.0, -1.0], 4) + data[1:, batch == 2] = np.nan + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + for kwargs in ({}, {"mean_only": True}, {"par_prior": False}): + out = combat(data, batch, **kwargs) + assert np.isfinite(out[~np.isnan(data)]).all() + + +@pytest.mark.parametrize("scale", [1e150, 1e200]) +def test_values_too_large_for_combat_are_rejected(scale: float) -> None: + """Values whose squares overflow are rejected with the feature named. + + Failure condition: ComBat returns non-finite values without an error. + """ + rng = np.random.default_rng(9) + data = rng.normal(10, 1, (20, 12)) + data[4] *= scale + with pytest.raises( + ValueError, match=r"magnitude 1e150 or more in 1 feature\(s\) \(first: \['4'\]\)" + ): + combat(data, np.repeat([0, 1, 2], 4)) + + +def test_harmonize_names_the_feature_too_large_for_combat() -> None: + """harmonize() with ComBat rejects such values before correcting, naming the feature; + limma corrects them. + + Failure condition: the run fails mid-way, or limma is refused although it is finite. + """ + import pandas as pd + + from harmonizepy import harmonize + + rng = np.random.default_rng(10) + samples = [f"s{i}" for i in range(12)] + data = pd.DataFrame( + rng.normal(10, 1, (20, 12)), columns=samples, index=[f"p{i}" for i in range(20)] + ) + data.iloc[3] *= 1e160 + desc = pd.DataFrame({"ID": samples, "sample": range(12), "batch": np.repeat([1, 2, 3], 4)}) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + with pytest.raises(ValueError, match=r"first: \['p3'\]"): + harmonize(data, desc) + out = harmonize(data, desc, algorithm="limma") + assert np.isfinite(out.to_numpy()).all() diff --git a/tests/test_comprehensive.py b/tests/test_comprehensive.py index ecb9c8d..6674d61 100644 --- a/tests/test_comprehensive.py +++ b/tests/test_comprehensive.py @@ -12,28 +12,28 @@ 8. spotting / splitting unit tests 9. Splitting integration 10. Singleton batch (R forces mean_only) - 11. needed_values parameter (Step 3) - 12. NaN propagation audit (Step 4) + 11. needed_values parameter + 12. Missing cells inside qualifying groups All R reference values are generated by generate_edgecase_fixtures.R. -Tolerance reference (Section 5.3) ----------------------------------- -Observed maximum absolute difference between Python and R outputs: +Tolerances +---------- +The tolerances the concordance tests assert, and why they differ: - Mode 1 (parametric, location+scale) rtol ~2e-5, atol ~1e-5 - Cause: iterative EM solver (_it_sol) reaches a different fixed point - within the same tolerance window as R's optim(). Every non-parametric - mode and the mean-only modes use closed-form or single-pass formulas - so agreement is at double-precision machine epsilon. + Mode 1 (parametric, location+scale) rtol 1e-4, atol 1e-5 + The empirical-Bayes estimates come from a fixed-point iteration (sva's + it.sol) that stops when the largest relative change falls below 1e-4, + with a stopping test that differs slightly from sva's, so the two stop + at nearby points. + Modes 2 and 4 (location only) rtol 1e-6, atol 1e-8 + Closed-form posterior means (mode 2) or one weighted average (mode 4). + Mode 3 (non-parametric, location+scale) rtol 1e-6, atol 1e-8; + 5e-4 and 1e-4 on the large input + One deterministic weighted average over the other features; the + large input needs the wider tolerance. - Mode 2 (parametric, location only) rtol ~1e-9, atol ~1e-9 - Mode 3 (non-parametric, location+scale) rtol ~2e-4, atol ~1e-4 - Cause: Monte-Carlo integration (_int_eprior) with finite n draws; - R uses a different random stream so the estimates differ slightly. - Mode 4 (non-parametric, location only) rtol ~1e-9, atol ~1e-9 - - limma (OLS, no iteration) rtol ~1e-9, atol ~1e-9 + limma (OLS, no iteration) rtol 1e-10, atol 1e-10 These tolerances are the reference for future changes; tighter values should not be used without understanding the cause. @@ -181,7 +181,7 @@ def test_vs_r_sva(self, dataset, mode): rtol = 5e-4 atol = 1e-4 - # R produces NaN for near-constant features (pooled var ≈ 0); + # R produces NaN for near-constant features (pooled var ~ 0); # our implementation clamps var_pooled > 0 and returns numbers. # Compare only where R produced non-NaN, then verify R-NaN rows # are from near-constant features (low within-batch variance). @@ -248,7 +248,7 @@ def test_batch_means_converge(self, dataset, mode): spread_before = max(means_before) - min(means_before) spread_after = max(means_after) - min(means_after) assert spread_after < spread_before + 1e-10, ( - f"{dataset} mode {mode}: spread not reduced {spread_before:.4f} → {spread_after:.4f}" + f"{dataset} mode {mode}: spread not reduced {spread_before:.4f} gives {spread_after:.4f}" ) @@ -614,7 +614,7 @@ def test_3d_input_rejected(self): with pytest.raises(ValueError, match="2-D"): combat(np.zeros((2, 3, 4)), np.array([0, 0, 1])) - def test_nan_rows_dropped(self): + def test_missing_cells_stay_missing_and_others_are_adjusted(self): """Per-cell NaN positions stay NaN; quantified cells are adjusted. Failure condition: quantified cells become NaN or NaN propagates. @@ -668,7 +668,7 @@ def test_invalid_ref_batch(self): combat(data, batch, ref_batch=99) def test_single_batch_returns_copy(self): - """Single batch → data returned unchanged.""" + """Single batch gives data returned unchanged.""" data = np.random.default_rng(2).normal(10, 2, size=(10, 4)) batch = np.array([0, 0, 0, 0]) result = combat(data, batch) @@ -736,7 +736,7 @@ def test_ref_batch_with_noncontiguous_labels(self): np.testing.assert_array_equal(result[:, ref_cols], data[:, ref_cols]) def test_identical_batches_no_change(self): - """If batches have no real effect, output should ≈ input.""" + """If batches have no real effect, output should ~ input.""" rng = np.random.default_rng(14) data = rng.normal(10, 1, size=(30, 8)) batch = np.array([0, 0, 0, 0, 1, 1, 1, 1]) @@ -1095,7 +1095,7 @@ def test_feature_only_one_batch_passthrough(self): } ) result = harmonize(data, desc, algorithm="ComBat", combat_mode=2) - # Feature 0 present only in batch 1 → single-batch passthrough → values unchanged + # Feature 0 present only in batch 1 gives single-batch passthrough gives values unchanged np.testing.assert_array_equal( result.iloc[0, :3].values, data.iloc[0, :3].values, @@ -1107,7 +1107,7 @@ def test_feature_only_one_batch_passthrough(self): assert not np.isnan(result.iloc[1:]).any(axis=None) def test_all_features_missing_returns_all_nan(self): - """All features entirely NaN → zero features pass spotting → all-NaN output, no crash.""" + """All features entirely NaN gives zero features pass spotting gives all-NaN output, no crash.""" data = pd.DataFrame( [[np.nan] * 4, [np.nan] * 4, [np.nan] * 4], index=["p0", "p1", "p2"], @@ -1125,8 +1125,8 @@ def test_all_features_missing_returns_all_nan(self): assert np.isnan(result.values).all(), "Expected all-NaN when all features are missing" def test_zero_features_pass_needed_values(self): - """Feature with only 1 value per batch fails nv=2 → NaN passthrough.""" - # batch 1: one sample per feature; batch 2: one sample per feature → nv=2 fails all + """Feature with only 1 value per batch fails nv=2 gives NaN passthrough.""" + # batch 1: one sample per feature; batch 2: one sample per feature gives nv=2 fails all data = pd.DataFrame( {"s0": [1.0, 2.0, 3.0], "s1": [4.0, 5.0, 6.0]}, index=["p0", "p1", "p2"], @@ -1139,7 +1139,7 @@ def test_zero_features_pass_needed_values(self): } ) result = harmonize(data, desc, algorithm="ComBat", combat_mode=1, needed_values=2) - # Each batch has only 1 sample, so needed_values=2 is never met → all NaN + # Each batch has only 1 sample, so needed_values=2 is never met gives all NaN assert result.shape == data.shape assert np.isnan(result.values).all(), "Expected all-NaN when no features meet needed_values" @@ -1255,7 +1255,7 @@ class TestSpottingEdgeCases: """ def test_no_missing(self): - """All data present → every feature sees all batches.""" + """All data present gives every feature sees all batches.""" data = pd.DataFrame(np.ones((5, 6))) batch = np.array([1, 1, 1, 2, 2, 2]) block = batch.copy() @@ -1263,7 +1263,7 @@ def test_no_missing(self): assert all(affil == (1, 2) for affil in result) def test_one_batch_all_nan(self): - """Feature entirely NaN in one batch → only other batch in affiliation.""" + """Feature entirely NaN in one batch gives only other batch in affiliation.""" data = pd.DataFrame(np.ones((3, 6))) data.iloc[0, 3:] = np.nan # Feature 0: NaN in batch 2 batch = np.array([1, 1, 1, 2, 2, 2]) @@ -1274,7 +1274,7 @@ def test_one_batch_all_nan(self): assert result[2] == (1, 2) def test_feature_insufficient_in_all_batches(self): - """Feature with < needed_values everywhere → empty affiliation.""" + """Feature with < needed_values everywhere gives empty affiliation.""" data = pd.DataFrame(np.ones((3, 6))) data.iloc[0, :] = np.nan batch = np.array([1, 1, 1, 2, 2, 2]) @@ -1325,7 +1325,7 @@ class TestSplittingRebuild: """ def test_no_missing_single_group(self): - """Complete data → one sub-df, result matches direct combat.""" + """Complete data gives one sub-df, result matches direct combat.""" rng = np.random.default_rng(60) data = pd.DataFrame( rng.normal(10, 2, size=(10, 6)), @@ -1364,7 +1364,7 @@ def test_partial_missing_produces_nans(self): assert not np.isnan(result.iloc[0, :6]).any() def test_all_missing_feature_stays_nan(self): - """Completely NaN feature → stays all NaN after splitting.""" + """Completely NaN feature gives stays all NaN after splitting.""" rng = np.random.default_rng(62) data = pd.DataFrame( rng.normal(10, 2, size=(5, 6)), @@ -1435,12 +1435,12 @@ def test_mean_only_matches_r(self, mode): # =================================================================== -# 11. needed_values parameter (Step 3) +# 11. needed_values parameter # =================================================================== class TestNeededValuesParameter: - """Step 3: verify needed_values threshold and auto-select logic. + """The needed_values threshold and the default chosen for each engine and mode. Helper datasets use unequal batch sizes so that changing the threshold genuinely includes or excludes specific batches: @@ -1500,10 +1500,10 @@ def _monotonic_data(): Features 4-5: absent in batches 2 and 3 Expected NaN cells in output by needed_values: - nv=1 → 8 (features 2-3 lose 1 col; features 4-5 lose 3 cols) - nv=2 → 10 (features 0-3 lose 1 col; features 4-5 lose 3 cols) - nv=3 → 18 (all 6 features passthrough, losing batches 2+3) - nv=4 → 36 (all batches excluded, everything NaN) + nv=1 gives 8 (features 2-3 lose 1 col; features 4-5 lose 3 cols) + nv=2 gives 10 (features 0-3 lose 1 col; features 4-5 lose 3 cols) + nv=3 gives 18 (all 6 features passthrough, losing batches 2+3) + nv=4 gives 36 (all batches excluded, everything NaN) """ rng = np.random.default_rng(42) data = pd.DataFrame( @@ -1602,9 +1602,9 @@ def test_mode1_mode2_auto_select_differ(self): data, desc = self._batch_data_9() result_mode1 = harmonize(data, desc, algorithm="ComBat", combat_mode=1) result_mode2 = harmonize(data, desc, algorithm="ComBat", combat_mode=2) - # Mode 1 (auto nv=2) excludes singleton → NaN in last column + # Mode 1 (auto nv=2) excludes singleton gives NaN in last column assert np.isnan(result_mode1.iloc[:, 8]).all() - # Mode 2 (auto nv=1) includes singleton → not all-NaN + # Mode 2 (auto nv=1) includes singleton gives not all-NaN assert not np.isnan(result_mode2.iloc[:, 8]).all() # ------------------------------------------------------------------ @@ -1616,21 +1616,22 @@ def test_explicit_nv3_overrides_mode1_auto(self): data, desc = self._batch_data_10() result_auto = harmonize(data, desc, algorithm="ComBat", combat_mode=1) result_nv3 = harmonize(data, desc, algorithm="ComBat", combat_mode=1, needed_values=3) - # Auto (nv=2) includes 2-sample batch → no NaN in cols 8-9 + # Auto (nv=2) includes 2-sample batch gives no NaN in cols 8-9 assert not np.isnan(result_auto.iloc[:, 8:]).any(axis=None) - # Explicit nv=3 excludes 2-sample batch → cols 8-9 all NaN + # Explicit nv=3 excludes 2-sample batch gives cols 8-9 all NaN assert np.isnan(result_nv3.iloc[:, 8:]).all(axis=None) def test_explicit_nv1_overrides_mode2_auto(self): - """Explicit nv=1 with mode=2 includes a batch that auto (nv=2, but wait: mode2 auto=1). + """Mode 2 defaults to needed_values=1 and keeps a one-sample batch; 2 drops it. - Re-framed: mode=1 auto=2 excludes singleton; explicit nv=1 on same mode includes it. + Failure condition: the mode 2 default is 2, or an explicit value does not + override it. """ data, desc = self._batch_data_9() - # Mode=2 auto → nv=1 → includes singleton + # Mode=2 auto gives nv=1 gives includes singleton result_auto = harmonize(data, desc, algorithm="ComBat", combat_mode=2) assert not np.isnan(result_auto.iloc[:, 8]).all() - # Mode=2 explicit nv=2 → excludes singleton + # Mode=2 explicit nv=2 gives excludes singleton result_nv2 = harmonize(data, desc, algorithm="ComBat", combat_mode=2, needed_values=2) assert np.isnan(result_nv2.iloc[:, 8]).all() @@ -1652,7 +1653,7 @@ def test_total_nan_increases_with_nv(self): # =================================================================== -# 12. NaN propagation audit (Step 4) +# 12. Missing cells inside qualifying groups # =================================================================== @@ -1660,10 +1661,9 @@ class TestNaNPropagation: """Per-cell NaN within qualifying affiliation groups reaches the engines and is handled. The core invariant: when a sub-matrix has per-cell NaN (stochastic dropout - within a block that passes the affiliation threshold), the engines must - handle it by dropping affected rows before computation (matching R - sva::ComBat's na.omit). Clean rows must be adjusted; rows with any NaN - stay all-NaN in the output. + within a block that passes the affiliation threshold), the engines fit each + feature on its observed cells, as R sva::ComBat does with Beta.NA. Every + feature is adjusted, and each missing cell stays missing in the output. """ @staticmethod @@ -1673,7 +1673,7 @@ def _structural_nan_data(): Feature 0: absent entirely in batch 3 (structural). Feature 1: absent entirely in batches 2+3 (structural). Features 2-9: fully present. - Feature 2: has per-cell NaN in sample 0 (batch 1) — stochastic dropout. + Feature 2: has per-cell NaN in sample 0 (batch 1), a scattered missing value. """ rng = np.random.default_rng(300) data = pd.DataFrame( @@ -1695,69 +1695,34 @@ def _structural_nan_data(): ) return data, desc - def test_per_cell_nan_reaches_combat_and_is_handled(self, monkeypatch): - """Engines receive NaN and correctly handle it (per-feature OLS). + def test_per_cell_nan_is_handled_by_combat(self): + """A missing cell inside a qualifying group stays missing; the feature's other cells are corrected. - Failure condition: NaN causes a crash, or clean cells are not - adjusted. + Failure condition: the missing cell causes a crash, spreads to other cells, + or the feature is left uncorrected. - R sva::ComBat v3.60.0 handles NaN per-feature via Beta.NA: - NaN observations are omitted from OLS per feature, not by - dropping entire rows. + R sva::ComBat 3.60.0 handles missing cells per feature through ``Beta.NA``: + they are omitted from each feature's fit, not dropped with the whole row. """ - import harmonizepy.splitting as split_mod - - original = split_mod.combat - received_nan = [] - - def spy(data, batch, *, par_prior=True, mean_only=False, ref_batch=None): - has_nan = np.isnan(data).any() - received_nan.append(has_nan) - return original( - data, batch, par_prior=par_prior, mean_only=mean_only, ref_batch=ref_batch - ) - - monkeypatch.setattr(split_mod, "combat", spy) - data, desc = self._structural_nan_data() result = harmonize(data, desc, algorithm="ComBat", combat_mode=2) + assert np.isnan(result.iloc[2, 0]) + assert not np.isnan(result.iloc[2, 1:]).any() + assert not np.allclose(result.iloc[2, 1:], data.iloc[2, 1:]) + assert not np.isnan(result.iloc[3:].values).any() - # Engines received at least one call with NaN - assert any(received_nan), "Engine should have received NaN data" - - # Feature 2 has per-cell NaN only in sample 0. - # Only cell [2, 0] stays NaN; the rest are adjusted. - assert np.isnan(result.iloc[2, 0]), "Per-cell NaN position stays NaN" - assert not np.isnan(result.iloc[2, 1:]).any(), "Quantified cells should be adjusted" - - # Features 3-9 (fully present) have no NaN - assert not np.isnan(result.iloc[3:].values).any(), ( - "Fully-present features should have no NaN in output" - ) - - def test_per_cell_nan_reaches_limma_and_is_handled(self, monkeypatch): - """limma engines receive NaN and correctly handle it (per-feature OLS).""" - import harmonizepy.splitting as split_mod - - original = split_mod.remove_batch_effect - received_nan = [] - - def spy(data, batch): - has_nan = np.isnan(data).any() - received_nan.append(has_nan) - return original(data, batch) - - monkeypatch.setattr(split_mod, "remove_batch_effect", spy) + def test_per_cell_nan_is_handled_by_limma(self): + """With limma, a missing cell stays missing and the feature's other cells are corrected. + Failure condition: the missing cell causes a crash, spreads to other cells, + or the feature is left uncorrected. + """ data, desc = self._structural_nan_data() result = harmonize(data, desc, algorithm="limma") - - assert any(received_nan), "Engine should have received NaN data" - assert np.isnan(result.iloc[2, 0]), "Per-cell NaN position stays NaN" - assert not np.isnan(result.iloc[2, 1:]).any(), "Quantified cells should be adjusted" - assert not np.isnan(result.iloc[3:].values).any(), ( - "Fully-present features should have no NaN in output" - ) + assert np.isnan(result.iloc[2, 0]) + assert not np.isnan(result.iloc[2, 1:]).any() + assert not np.allclose(result.iloc[2, 1:], data.iloc[2, 1:]) + assert not np.isnan(result.iloc[3:].values).any() def test_fully_present_features_no_nan_in_output(self): """Features fully present in all batches have no NaN in output. @@ -1796,7 +1761,7 @@ def test_output_nan_confined_to_absent_batch_columns(self): def _concordance_check(result, expected, rtol, atol, label): - """Shared NaN + allclose assertion for all Phase 2 concordance tests.""" + """Assert equal NaN positions and values within tolerance on the features both outputs share.""" shared_idx = result.index.intersection(expected.index) shared_cols = result.columns.intersection(expected.columns) r = result.loc[shared_idx, shared_cols].values @@ -2079,3 +2044,47 @@ def test_ur_false_feature_count_equals_r(self): assert len(result) == len(expected), ( f"Python ur=False: {len(result)}, R ur=False: {len(expected)}" ) + + +@pytest.mark.skipif( + not _fixture_exists("percell_nan_combat_mode1.tsv"), + reason="Per-cell NaN R fixtures not generated (run generate_edgecase_fixtures.R)", +) +class TestPerCellNaNRConcordance: + """Per-cell missing cells inside qualifying groups vs R HarmonizR 1.10.0. + + 30 features x 9 samples in 3 batches of 3; the first 10 features miss one + sample per batch and keep two values in each, so every feature stays in + one group and is fitted on its observed cells (sva's Beta.NA). + """ + + @pytest.mark.parametrize( + ("algorithm", "mode", "fixture"), + [ + ("ComBat", 1, "percell_nan_combat_mode1.tsv"), + ("ComBat", 2, "percell_nan_combat_mode2.tsv"), + ("ComBat", 3, "percell_nan_combat_mode3.tsv"), + ("ComBat", 4, "percell_nan_combat_mode4.tsv"), + ("limma", 1, "percell_nan_limma.tsv"), + ], + ) + def test_matches_harmonizr(self, algorithm, mode, fixture): + """Rows, columns, missing cells, and values match the HarmonizR output. + + Failure condition: a feature with a missing cell is dropped, emptied, + or corrected differently from R, or a missing cell is filled. + + Tolerances: rtol 1e-4 for mode 1, whose solver stops at a 1e-4 + convergence threshold; 1e-8 for the closed-form and non-parametric + modes and limma. + """ + data = _load_tsv_df("percell_nan_input.tsv") + desc = pd.read_csv(FIXTURE_DIR / "percell_nan_batch.csv") + expected = _load_tsv_df(fixture) + + result = harmonize(data, desc, algorithm=algorithm, combat_mode=mode) + + assert result.index.tolist() == expected.index.tolist() + assert result.columns.tolist() == expected.columns.tolist() + rtol = 1e-4 if (algorithm, mode) == ("ComBat", 1) else 1e-8 + _concordance_check(result, expected, rtol=rtol, atol=1e-8, label=fixture) diff --git a/tests/test_io.py b/tests/test_io.py index c1586d4..a430e62 100644 --- a/tests/test_io.py +++ b/tests/test_io.py @@ -5,13 +5,16 @@ from __future__ import annotations +import logging +import time from pathlib import Path import numpy as np import pandas as pd import pytest -from harmonizepy.io import read_description, read_main_data, write_output +from harmonizepy import harmonize +from harmonizepy.io import clean_features, read_description, read_main_data, write_output # --------------------------------------------------------------------------- # read_main_data @@ -71,20 +74,19 @@ def test_fallback_extension_tsv(self, tmp_path: Path) -> None: result = read_main_data(str(path)) pd.testing.assert_frame_equal(result, expected) - def test_drops_all_nan_rows(self, tmp_path: Path) -> None: - """Rows that are entirely NaN are removed on read. + def test_keeps_all_nan_rows(self, tmp_path: Path) -> None: + """Rows that are entirely missing are kept, as for a DataFrame passed directly. - Failure condition: all-NaN rows are kept in the returned - DataFrame, violating the documented contract. + Failure condition: a file and the same frame give matrices with different rows. """ df = pd.DataFrame( {"s1": [1.0, np.nan], "s2": [2.0, np.nan]}, - index=["keep", "drop"], + index=["kept", "blank"], ) path = _write_tsv(tmp_path / "data.tsv", df) result = read_main_data(str(path)) - assert "drop" not in result.index - assert "keep" in result.index + assert list(result.index) == ["kept", "blank"] + assert result.loc["blank"].isna().all() def test_preserves_all_nan_columns(self, tmp_path: Path) -> None: """All-NaN sample columns are kept as structural missingness. @@ -110,16 +112,16 @@ def test_file_not_found(self) -> None: with pytest.raises(FileNotFoundError): read_main_data("/nonexistent/file.tsv") - def test_empty_file_after_dropna(self, tmp_path: Path) -> None: - """File with only all-NaN rows returns an empty DataFrame. + def test_file_of_blank_rows_keeps_them(self, tmp_path: Path) -> None: + """A file whose only row is blank is read as one missing row. - Failure condition: all-NaN rows are dropped and the result - is an empty structure, or the function crashes on empty input. + Failure condition: the reader drops the row or fails on a matrix without values. """ df = pd.DataFrame({"s1": [np.nan], "s2": [np.nan]}, index=["f1"]) path = _write_tsv(tmp_path / "empty.tsv", df) result = read_main_data(str(path)) - assert len(result) == 0 + assert list(result.index) == ["f1"] + assert result.isna().all().all() # --------------------------------------------------------------------------- @@ -182,3 +184,370 @@ def test_write_empty_df(self, tmp_path: Path) -> None: write_output(df, str(path)) assert path.exists() # to_csv on an empty DataFrame produces a header-only file (>0 bytes) + + +class TestRepeatedFeatures: + """Repeated feature names, removed only when their values also match.""" + + def test_identical_values_different_names_both_kept(self, tmp_path: Path) -> None: + """Two features with identical values and different names are both kept. + + Failure condition: a feature is removed because its values match another's. + """ + path = tmp_path / "m.tsv" + path.write_text("id\ts1\ts2\ts3\np1\t1\t2\t3\np2\t1\t2\t3\np3\t4\t5\t6\n") + assert list(read_main_data(str(path)).index) == ["p1", "p2", "p3"] + + def test_same_name_and_values_removed_and_logged( + self, + tmp_path: Path, + caplog: pytest.LogCaptureFixture, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """A repeated feature with identical values is removed, and the removal is logged. + + Failure condition: the repeat stays in the matrix, or the removal is silent. + """ + # The command line turns off propagation on the package logger, and caplog + # only sees records that propagate to the root logger. + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + path = tmp_path / "m.tsv" + path.write_text("id\ts1\ts2\ts3\np1\t1\t2\t3\np1\t1\t2\t3\np3\t4\t5\t6\n") + with caplog.at_level(logging.INFO, logger="harmonizepy.io"): + result = read_main_data(str(path)) + assert list(result.index) == ["p1", "p3"] + assert "Removed 1 repeated feature(s) with identical values: p1" in caplog.text + + def test_same_name_different_values_raises(self, tmp_path: Path) -> None: + """A name repeated with different values is an error. + + Failure condition: the matrix is read and one of the two rows is silently kept. + """ + path = tmp_path / "m.tsv" + path.write_text("id\ts1\ts2\ts3\np1\t1\t2\t3\np1\t1\t2\t9\n") + with pytest.raises(ValueError, match="duplicate feature names with different values"): + read_main_data(str(path)) + + def test_missing_cells_in_the_same_places_count_as_identical(self) -> None: + """Repeats with missing cells in the same places are identical; elsewhere they differ. + + Failure condition: missing cells make identical repeats look different, or + a missing cell matches a value. + """ + same = pd.DataFrame([[1.0, np.nan], [1.0, np.nan]], index=["a", "a"]) + assert len(clean_features(same)) == 1 + differs = pd.DataFrame([[1.0, np.nan], [1.0, 2.0]], index=["a", "a"]) + with pytest.raises(ValueError, match="'a'"): + clean_features(differs) + + def test_harmonize_removes_identical_repeat_from_a_dataframe(self) -> None: + """``harmonize()`` applies the same rule to a DataFrame passed directly. + + Failure condition: the repeat raises, or reaches the engines as two features. + """ + rng = np.random.default_rng(4) + samples = [f"s{i}" for i in range(1, 7)] + data = pd.DataFrame( + rng.normal(10, 1, (5, 6)), index=[f"p{i}" for i in range(5)], columns=samples + ) + repeated = pd.concat([data, data.iloc[[0]]]) + desc = pd.DataFrame({"ID": samples, "sample": range(1, 7), "batch": [1, 1, 1, 2, 2, 2]}) + with_repeat = harmonize(repeated, desc, algorithm="limma") + pd.testing.assert_frame_equal(with_repeat, harmonize(data, desc, algorithm="limma")) + + def test_non_numeric_columns_use_the_same_rule(self) -> None: + """With a text column, identical repeats are removed and differing ones raise. + + Failure condition: the check for frames that are not all numeric drops a + differing row or keeps an identical repeat. + """ + same = pd.DataFrame({"s1": [1.0, 1.0, 2.0], "note": ["x", "x", "y"]}, index=["a", "a", "b"]) + assert list(clean_features(same).index) == ["a", "b"] + differs = pd.DataFrame({"s1": [1.0, 1.0], "note": ["x", "z"]}, index=["a", "a"]) + with pytest.raises(ValueError, match="'a'"): + clean_features(differs) + + def test_name_repeated_once_blank_raises(self, tmp_path: Path) -> None: + """A name repeated with values and then with only blanks is a conflict. + + Failure condition: the blank row is dropped first and the conflict is never + reported. + """ + path = tmp_path / "m.tsv" + path.write_text("id\ts1\ts2\ts3\np1\t1\t2\t3\np1\t\t\t\np2\t4\t5\t6\n") + with pytest.raises(ValueError, match="'p1'"): + read_main_data(str(path)) + + def test_large_number_of_repeated_names_is_fast(self) -> None: + """Checking 20,000 repeated names takes well under a second. + + Failure condition: the check scans the index once per repeated name, which + takes tens of seconds at this size. + """ + values = np.random.default_rng(5).normal(size=(20_000, 4)) + frame = pd.DataFrame( + np.vstack([values, values]), index=[f"p{i}" for i in range(20_000)] * 2 + ) + start = time.perf_counter() + result = clean_features(frame) + # A generous bound, so that a loaded machine does not fail the test. + assert time.perf_counter() - start < 5.0 + assert len(result) == 20_000 + + +class TestIntegerColumns: + """Columns of whole numbers in the data matrix and the description.""" + + @pytest.mark.parametrize("ext", ["tsv", "csv", "parquet"]) + def test_integer_column_with_blank_loads_as_missing(self, tmp_path: Path, ext: str) -> None: + """A whole-number column with a blank cell loads, and the blank is missing. + + Failure condition: the reader raises on the blank cell. + """ + frame = pd.DataFrame( + {"s1": pd.array([1, None, 6], dtype="Int64"), "s2": [2, 4, 7], "s3": [3, 5, 8]}, + index=pd.Index(["p1", "p2", "p3"], name="id"), + ) + path = tmp_path / f"m.{ext}" + if ext == "parquet": + pytest.importorskip("pyarrow") + frame.to_parquet(path) + else: + frame.to_csv(path, sep="\t" if ext == "tsv" else ",") + result = read_main_data(str(path)) + assert result["s1"].dtype == np.float64 + assert np.isnan(result.loc["p2", "s1"]) + assert result["s1"].tolist()[::2] == [1.0, 6.0] + + def test_wide_and_narrow_readers_agree(self, tmp_path: Path) -> None: + """Both readers give the same frame for whole-number and blank columns. + + Failure condition: the dtype of a column depends on how many columns the + file has, or a column of blanks is read as text by one reader. + """ + + def write(n_cols: int, path: Path) -> pd.DataFrame: + cols = [f"s{i}" for i in range(n_cols)] + rows = { + "p1": ["", ""] + ["1"] * (n_cols - 2), + "p2": ["2", ""] + ["2"] * (n_cols - 2), + } + lines = ["id\t" + "\t".join(cols)] + lines += [name + "\t" + "\t".join(vals) for name, vals in rows.items()] + path.write_text("\n".join(lines) + "\n") + return read_main_data(str(path)) + + wide = write(501, tmp_path / "wide.tsv") + narrow = write(4, tmp_path / "narrow.tsv") + for col in ["s0", "s1", "s2"]: + assert wide[col].dtype == narrow[col].dtype, col + assert narrow["s0"].dtype == np.float64 + assert narrow["s1"].dtype == np.float64 + assert narrow["s2"].dtype == np.int64 + + def test_integer_column_without_blank_stays_integer(self, tmp_path: Path) -> None: + """A whole-number column without a blank keeps an integer dtype. + + Failure condition: integer columns become floating point without a blank, + so the dtype depends on the reader. + """ + path = tmp_path / "m.tsv" + path.write_text("id\ts1\ts2\np1\t1\t2\np2\t3\t4\n") + assert read_main_data(str(path))["s1"].dtype == np.int64 + + def test_description_keeps_integer_columns(self, tmp_path: Path) -> None: + """The batch description keeps its integer columns. + + Failure condition: batch labels are read as floating point. + """ + path = tmp_path / "d.csv" + path.write_text("ID,sample,batch\ns1,1,1\ns2,2,2\n") + desc = read_description(str(path)) + assert desc["batch"].dtype == np.int64 + assert desc["sample"].dtype == np.int64 + + +@pytest.mark.parametrize("ext, sep", [("tsv", "\t"), ("csv", ",")]) +def test_repeated_sample_name_in_file_raises(tmp_path: Path, ext: str, sep: str) -> None: + """A sample name repeated in a file header is rejected by name. + + Failure condition: the parser renames the second column to ``s1.1`` and the + run treats the two columns as different samples. + """ + path = tmp_path / f"m.{ext}" + header = sep.join(["id", "s1", "s1", "s2"]) + path.write_text(f"{header}\n" + sep.join(["p1", "1", "2", "3"]) + "\n") + with pytest.raises(ValueError, match=r"duplicate sample names: \['s1'\]"): + read_main_data(str(path)) + + +@pytest.mark.parametrize( + "name, fmt", + [ + ("a.tsv", "tsv"), + ("a.TXT", "tsv"), + ("a.csv", "csv"), + ("a.CSV", "csv"), + ("a.pq", "parquet"), + ("a.parquet", "parquet"), + ("a.dat", "tsv"), + ("a", "tsv"), + ], +) +def test_format_from_suffix(name: str, fmt: str) -> None: + """The output format follows the suffix, case-insensitively, and is TSV otherwise. + + Failure condition: the CLI and ``write_output`` disagree on a suffix's format. + """ + from harmonizepy.io import format_from_suffix + + assert format_from_suffix(name) == fmt + + +@pytest.mark.parametrize("fmt, sep", [("tsv", "\t"), ("csv", ",")]) +def test_write_frame_writes_the_named_format(tmp_path: Path, fmt: str, sep: str) -> None: + """``write_frame`` writes the requested format whatever the suffix. + + Failure condition: the suffix overrides the requested format. + """ + from harmonizepy.io import write_frame + + path = tmp_path / "out.dat" + write_frame(pd.DataFrame({"s1": [1.0], "s2": [2.0]}, index=["p1"]), str(path), fmt) + assert path.read_text().splitlines()[0].count(sep) == 2 + + +def test_reading_a_delimited_file_starts_no_threads(tmp_path: Path) -> None: + """Reading a TSV and a CSV runs on the calling thread and leaves no new thread behind. + + Failure condition: the reader starts a thread pool, as pyarrow's CSV reader does. + """ + tasks = Path("/proc/self/task") + if not tasks.is_dir(): + pytest.skip("thread listing needs /proc") + data_path = tmp_path / "m.tsv" + data_path.write_text("id\ts1\ts2\ts3\np1\t1\t2\t3\np2\t4\t5\t6\n") + desc_path = tmp_path / "d.csv" + desc_path.write_text("ID,sample,batch\ns1,1,1\ns2,2,1\ns3,3,2\n") + before = set(tasks.iterdir()) + read_main_data(str(data_path)) + read_description(str(desc_path)) + assert set(tasks.iterdir()) <= before + + +class TestNamesReadAsWritten: + """Feature names and description IDs are text, read exactly as in the file.""" + + def test_feature_names_that_look_missing_are_kept(self, tmp_path: Path) -> None: + """Rows named NA and null keep their names; NA in a value cell is still missing. + + Failure condition: the reader applies its missing-value markers to the + name column, so both rows are named NaN and one is removed as a repeat. + """ + path = tmp_path / "data.tsv" + path.write_text("feature\ts1\ts2\nNA\t1\t2\nnull\t1\t2\nf3\t3\tNA\n") + + result = read_main_data(str(path)) + + assert result.index.tolist() == ["NA", "null", "f3"] + assert np.isnan(result.loc["f3", "s2"]) + + def test_numeric_looking_feature_names_stay_text(self, tmp_path: Path) -> None: + """Feature names such as 001 and 002 are not turned into numbers. + + Failure condition: the name column is type-inferred, so 001 becomes 1. + """ + path = tmp_path / "data.tsv" + path.write_text("feature\ts1\ts2\n001\t1\t2\n002\t3\t4\n") + + result = read_main_data(str(path)) + + assert result.index.tolist() == ["001", "002"] + + def test_numeric_looking_sample_ids_match_the_header(self, tmp_path: Path) -> None: + """Description IDs 01 to 04 match data columns 01 to 04 and the run succeeds. + + Failure condition: the ID column is type-inferred, so 01 becomes 1 and + the run is refused with a mismatch the user did not make. + """ + ids = ["01", "02", "03", "04"] + data = pd.DataFrame( + np.random.default_rng(3).normal(10, 1, (6, 4)), + index=[f"f{i}" for i in range(6)], + columns=ids, + ) + data_path = _write_tsv(tmp_path / "data.tsv", data) + desc_path = tmp_path / "desc.csv" + desc_path.write_text("ID,sample,batch\n01,1,1\n02,2,1\n03,3,2\n04,4,2\n") + + assert read_description(str(desc_path))["ID"].tolist() == ids + result = harmonize(str(data_path), str(desc_path), algorithm="limma") + assert result.columns.tolist() == ids + + +class TestAtomicWrites: + """A write that fails part way leaves no partial file under the user's name.""" + + @staticmethod + def _failing_to_csv(self: pd.DataFrame, path: str, *args: object, **kwargs: object) -> None: + Path(path).write_text("partial") + raise OSError("disk full") + + def test_failed_write_keeps_the_existing_file( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """An existing output keeps its content when a new write fails. + + Failure condition: the writer opens the target directly, so the old + file is truncated and replaced by a partial one. + """ + target = tmp_path / "out.tsv" + target.write_text("previous run") + # File I/O is an owned boundary: the patched writer fails after writing. + monkeypatch.setattr(pd.DataFrame, "to_csv", self._failing_to_csv) + + with pytest.raises(OSError, match="disk full"): + write_output(pd.DataFrame({"s1": [1.0]}, index=["f1"]), str(target)) + + assert target.read_text() == "previous run" + assert sorted(p.name for p in tmp_path.iterdir()) == ["out.tsv"] + + def test_failed_write_creates_no_file( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A failed write to a new path leaves nothing behind. + + Failure condition: a partial file or the temporary file stays in the folder. + """ + monkeypatch.setattr(pd.DataFrame, "to_csv", self._failing_to_csv) + + with pytest.raises(OSError, match="disk full"): + write_output(pd.DataFrame({"s1": [1.0]}, index=["f1"]), str(tmp_path / "new.csv")) + + assert list(tmp_path.iterdir()) == [] + + def test_successful_write_leaves_only_the_target(self, tmp_path: Path) -> None: + """A normal write produces the target and no temporary file. + + Failure condition: the temporary file is not renamed or not removed. + """ + df = pd.DataFrame({"s1": [1.0, 2.0]}, index=["f1", "f2"]) + + write_output(df, str(tmp_path / "out.tsv")) + + assert [p.name for p in tmp_path.iterdir()] == ["out.tsv"] + pd.testing.assert_frame_equal(read_main_data(str(tmp_path / "out.tsv")), df) + + def test_missing_folder_error_names_the_target(self, tmp_path: Path) -> None: + """Writing into a missing folder raises an error that names the given path. + + Failure condition: the message names the hidden temporary file, which + the user never asked for. + """ + target = tmp_path / "missing" / "out.tsv" + + with pytest.raises(FileNotFoundError) as caught: + write_output(pd.DataFrame({"s1": [1.0]}, index=["f1"]), str(target)) + + assert caught.value.filename == str(target) + assert ".tmp" not in str(caught.value) diff --git a/tests/test_limma.py b/tests/test_limma.py index 10b03a0..66b3766 100644 --- a/tests/test_limma.py +++ b/tests/test_limma.py @@ -8,6 +8,7 @@ from __future__ import annotations +import logging from pathlib import Path import numpy as np @@ -33,32 +34,25 @@ def make_test_data(n_proteins=50, n_samples_per_batch=5, n_batches=3, seed=42): def _remove_batch_effect_nan_reference(data: np.ndarray, batch: np.ndarray) -> np.ndarray: - """Per-feature NaN-safe limma reference used to fence grouped solves.""" - unique_batches = np.unique(batch) - n_batch = len(unique_batches) - if n_batch < 2: - return data.copy() + """Per-feature limma reference: sum-to-zero contrasts over the batches each feature is observed in. - label_map = {b: i for i, b in enumerate(unique_batches)} - batch_idx = np.array([label_map[b] for b in batch], dtype=np.intp) - - x_batch = np.zeros((data.shape[1], n_batch - 1), dtype=np.float64) - for j in range(n_batch - 1): - x_batch[batch_idx == j, j] = 1.0 - x_batch[batch_idx == n_batch - 1, :] = -1.0 - - design = np.hstack([np.ones((data.shape[1], 1), dtype=np.float64), x_batch]) + A feature observed in one batch only is returned as given. + """ corrected = data.copy() for row_index in range(data.shape[0]): y = data[row_index, :] valid = ~np.isnan(y) - if valid.sum() < n_batch: + labels, batch_idx = np.unique(batch[valid], return_inverse=True) + n_batch = len(labels) + if n_batch < 2: continue - des = design[valid, :] - y1 = y[valid] - beta = np.linalg.lstsq(des, y1, rcond=None)[0] - beta_batch = np.nan_to_num(beta[1:], nan=0.0) - corrected[row_index, valid] = y1 - x_batch[valid, :] @ beta_batch + x_batch = np.zeros((int(valid.sum()), n_batch - 1), dtype=np.float64) + for j in range(n_batch - 1): + x_batch[batch_idx == j, j] = 1.0 + x_batch[batch_idx == n_batch - 1, :] = -1.0 + design = np.hstack([np.ones((int(valid.sum()), 1)), x_batch]) + beta = np.linalg.lstsq(design, y[valid], rcond=None)[0] + corrected[row_index, valid] = y[valid] - x_batch @ beta[1:] return corrected @@ -250,3 +244,138 @@ def test_vs_r_limma(self): atol=1e-10, err_msg="Mismatch vs R limma::removeBatchEffect", ) + + +class TestLimmaInputs: + """Batch labels and rows limma cannot fit.""" + + @pytest.mark.parametrize("labels", [[0.2, 0.2, 0.9, 0.9], ["a", "a", "b", "b"]]) + def test_labels_that_are_not_whole_numbers_raise(self, labels: list[object]) -> None: + """Fractional and text batch labels are rejected, as in ComBat. + + Failure condition: limma accepts labels ComBat rejects. + """ + data = np.random.default_rng(11).normal(size=(5, 4)) + with pytest.raises(ValueError, match=r"batch labels must be whole numbers below 2\*\*53"): + remove_batch_effect(data, labels) + + def test_feature_missing_a_batch_is_fitted_on_its_observed_batches(self) -> None: + """A feature with no value in one batch is levelled across the batches it has. + + Failure condition: the unobserved batch enters the fit and pulls the + feature's level towards zero. + """ + rng = np.random.default_rng(12) + batch = np.repeat([0, 1, 2], 4) + shift = np.array([0.0, 1.0, -1.0])[batch] + data = rng.normal(10, 0.3, (200, 12)) + rng.normal(0, 0.5, (200, 1)) + shift + data[0, batch == 2] = np.nan + keep = batch < 2 + out = remove_batch_effect(data, batch) + alone = remove_batch_effect(data[:, keep], batch[keep]) + np.testing.assert_allclose(out[0, keep], alone[0], rtol=1e-12) + + def test_feature_missing_a_batch_without_residual_is_left_raw( + self, caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch + ) -> None: + """A feature missing a batch with one value per observed batch keeps its values. + + Fitting it would leave no residual and collapse its values to one level. + + Failure condition: the values 10 and 11 both come back as 10.5. + """ + # The command line turns off propagation on the package logger, and caplog + # only sees records that propagate to the root logger. + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + rng = np.random.default_rng(33) + data = rng.normal(5, 1, (4, 6)) + data[3] = [10.0, np.nan, 11.0, np.nan, np.nan, np.nan] + with caplog.at_level(logging.INFO, logger="harmonizepy.limma_wrapper"): + out = remove_batch_effect(data, np.repeat([0, 1, 2], 2)) + np.testing.assert_array_equal(out[3], data[3]) + assert "1 with no more values than observed batches" in caplog.text + + def test_feature_observed_in_one_batch_is_left_raw(self) -> None: + """A feature with values in a single batch has no batch effect to remove. + + Failure condition: the feature is shifted although nothing can be estimated. + """ + data = np.array([[1.0, 2.0, np.nan, np.nan], [1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 1.0, 0.0]]) + out = remove_batch_effect(data, [0, 0, 1, 1]) + np.testing.assert_array_equal(out[0], data[0]) + + +def test_contrast_design_sums_to_zero() -> None: + """Each sum-to-zero batch column sums to zero over balanced batches, and the last batch is -1. + + Failure condition: the contrast coding differs from R's ``contr.sum``. + """ + from harmonizepy.limma_wrapper import _contrast_design + + design, x_batch = _contrast_design(np.array([5, 5, 7, 7, 9, 9])) + np.testing.assert_array_equal(design[:, 0], np.ones(6)) + np.testing.assert_array_equal(x_batch[:, 0], [1, 1, 0, 0, -1, -1]) + np.testing.assert_array_equal(x_batch[:, 1], [0, 0, 1, 1, -1, -1]) + + +def test_log_counts_a_feature_with_no_value_apart_from_single_batch( + caplog: pytest.LogCaptureFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + """A feature with no value is not counted as having values in a single batch. + + Failure condition: the log reports two single-batch features where one has no + value at all. + """ + monkeypatch.setattr(logging.getLogger("harmonizepy"), "propagate", True) + rng = np.random.default_rng(8) + batch = np.repeat([0, 1, 2], 3) + data = rng.normal(10, 1, (6, 9)) + data[0] = np.nan + data[1, batch > 0] = np.nan + with caplog.at_level(logging.INFO, logger="harmonizepy.limma_wrapper"): + out = remove_batch_effect(data, batch) + assert "1 feature(s) left uncorrected: 1 with values in a single batch" in caplog.text + assert np.isnan(out[0]).all() + + +def test_feature_with_one_value_per_batch_is_left_raw() -> None: + """A feature present in every batch with one value each keeps its values. + + Failure condition: the fit leaves no residual and every value comes back as + the mean of the batch means. + """ + rng = np.random.default_rng(12) + batch = np.repeat([0, 1, 2], 2) + data = rng.normal(5, 1, (4, 6)) + data[3] = [10.0, np.nan, 11.0, np.nan, 12.0, np.nan] + out = remove_batch_effect(data, batch) + np.testing.assert_array_equal(out[3], data[3]) + + +def test_complete_matrix_with_one_sample_per_batch_is_left_raw() -> None: + """Without missing cells, one sample per batch leaves no residual, so nothing is corrected. + + Failure condition: every feature collapses to a constant row. + """ + data = np.random.default_rng(13).normal(5, 1, (5, 3)) + np.testing.assert_array_equal(remove_batch_effect(data, np.array([0, 1, 2])), data) + + +def test_report_names_limma_features_with_too_few_values() -> None: + """harmonize() with limma reports a feature with one value per batch as raw. + + Failure condition: the report says ``corrected`` for a feature the fit collapsed. + """ + from harmonizepy import harmonize + + rng = np.random.default_rng(14) + samples = [f"s{i}" for i in range(6)] + data = pd.DataFrame( + rng.normal(5, 1, (6, 6)), index=[f"f{i}" for i in range(6)], columns=samples + ) + data.iloc[:2, [1, 3, 5]] = np.nan + desc = pd.DataFrame({"ID": samples, "sample": range(6), "batch": [1, 1, 2, 2, 3, 3]}) + out, report = harmonize(data, desc, algorithm="limma", needed_values=1, return_report=True) + assert (report.loc[["f0", "f1"], "status"] == "raw_too_few_values").all() + pd.testing.assert_frame_equal(out.loc[["f0", "f1"]], data.loc[["f0", "f1"]]) + assert (report.loc[["f2", "f3", "f4", "f5"], "status"] == "corrected").all() diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index aa17425..2830eac 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -1,6 +1,6 @@ """Integration tests for the full HarmonizePy pipeline. -Tests the complete spotting → splitting → adjust → concat flow via +Tests the complete spotting -> splitting -> adjust -> concat flow via ``harmonize()`` and validates against R HarmonizR fixtures. """ @@ -18,6 +18,7 @@ FIXTURE_DIR = Path(__file__).parent / "fixtures" _has_small = (FIXTURE_DIR / "small_combat_mode1.tsv").exists() _has_medium = (FIXTURE_DIR / "medium_harmonizr_combat_mode1.tsv").exists() +_has_small_input = (FIXTURE_DIR / "small_input.tsv").exists() # --------------------------------------------------------------------------- @@ -36,9 +37,9 @@ def test_combat_modes(self, mode): Failure condition: the pipeline produces different corrected values than the reference R implementation. - Tolerances: rtol=1e-4/atol=1e-6 for parametric iterative modes - (1, 3); closed-form modes (2, 4) converge tighter but this - single tolerance covers all modes safely. + Tolerances: rtol=1e-4/atol=1e-6 for mode 1, whose parametric + solver iterates to a 1e-4 convergence threshold; the other modes + agree more closely, but this single tolerance covers all modes. """ result = harmonize( str(FIXTURE_DIR / "small_input.tsv"), @@ -121,15 +122,10 @@ def test_combat_modes_with_missing(self, mode): index_col=0, ) assert result.shape == expected.shape - - assert ( - result.isna().sum(axis=1).value_counts().to_dict() - == expected.isna().sum(axis=1).value_counts().to_dict() - ) - - common = result.index.intersection(expected.index) - r = result.loc[common] - e = expected.loc[common] + assert set(result.index) == set(expected.index) + r = result.loc[expected.index, expected.columns] + e = expected + pd.testing.assert_frame_equal(r.isna(), e.isna()) mask = r.notna() & e.notna() np.testing.assert_allclose( r.values[mask.values], @@ -145,30 +141,35 @@ def test_combat_modes_with_missing(self, mode): # --------------------------------------------------------------------------- -@pytest.mark.skipif(not _has_small, reason="R fixtures not generated") +@pytest.mark.skipif(not _has_small_input, reason="small input fixture missing") class TestDataFrameInput: def test_dataframe_input(self): - """DataFrame input must produce identical results to file-path input. + """DataFrame input gives exactly the result of file-path input. Failure condition: the internal code path for DataFrames differs from the file-path path (e.g. index handling, dtype casting). - - Tolerances: rtol=1e-4/atol=1e-6 match the R concordance tolerance. """ data = pd.read_csv(FIXTURE_DIR / "small_input.tsv", sep="\t", index_col=0) desc = pd.read_csv(FIXTURE_DIR / "small_batch.csv") - result = harmonize(data, desc, algorithm="ComBat", combat_mode=1) - expected = pd.read_csv( - FIXTURE_DIR / "small_combat_mode1.tsv", - sep="\t", - index_col=0, - ) - np.testing.assert_allclose( - result.values, - expected.values, - rtol=1e-4, - atol=1e-6, + from_frame = harmonize(data, desc, algorithm="ComBat", combat_mode=1) + from_path = harmonize( + str(FIXTURE_DIR / "small_input.tsv"), + str(FIXTURE_DIR / "small_batch.csv"), + algorithm="ComBat", + combat_mode=1, ) + pd.testing.assert_frame_equal(from_frame, from_path) + + @pytest.mark.parametrize("sort", ["sparsity", "jaccard", "seriation"]) + def test_sort_without_block_changes_nothing(self, sort): + """Sorting without blocking gives exactly the unsorted output. + + Failure condition: the sort order leaks into the groups or the column + order although no block is formed. + """ + data = pd.read_csv(FIXTURE_DIR / "small_input.tsv", sep="\t", index_col=0) + desc = pd.read_csv(FIXTURE_DIR / "small_batch.csv") + pd.testing.assert_frame_equal(harmonize(data, desc, sort=sort), harmonize(data, desc)) def test_output_file(self, tmp_path): """output_file must write a TSV that matches the in-memory result. @@ -620,12 +621,11 @@ def test_ur_true_vs_r(self): combat_mode=1, unique_removal=True, ) - shared_idx = result.index.intersection(expected.index) - shared_cols = result.columns.intersection(expected.columns) - r = result.loc[shared_idx, shared_cols].values - e = expected.loc[shared_idx, shared_cols].values + assert set(result.index) == set(expected.index), "Rows differ from R" + r = result.loc[expected.index, expected.columns].values + e = expected.values nan_mask = np.isnan(e) - assert np.isnan(r[nan_mask]).all(), "Expected NaN where R has NaN" + np.testing.assert_array_equal(np.isnan(r), nan_mask, "Missing cells differ from R") valid = ~nan_mask if valid.any(): np.testing.assert_allclose( @@ -646,12 +646,11 @@ def test_ur_false_vs_r(self): combat_mode=1, unique_removal=False, ) - shared_idx = result.index.intersection(expected.index) - shared_cols = result.columns.intersection(expected.columns) - r = result.loc[shared_idx, shared_cols].values - e = expected.loc[shared_idx, shared_cols].values + assert set(result.index) == set(expected.index), "Rows differ from R" + r = result.loc[expected.index, expected.columns].values + e = expected.values nan_mask = np.isnan(e) - assert np.isnan(r[nan_mask]).all(), "Expected NaN where R has NaN" + np.testing.assert_array_equal(np.isnan(r), nan_mask, "Missing cells differ from R") valid = ~nan_mask if valid.any(): np.testing.assert_allclose( @@ -683,10 +682,13 @@ def _load(self): def test_combined_stress_vs_r(self): """Full stress test: sparsity sort + block=2 + ur=True + per-cell NaN. - Non-NaN values on matching cells must agree with R. NaN positions - may differ on a small fraction of features (documented edge case - with sort+block+ur+per-cell NaN combined). The test reports the - number of diverging features but only fails if a majority diverge. + Every row R returns is returned, and values agree with R on features + whose missing cells match. The sort order and the unique-removal rule + differ from R, so up to 20 of the 50 features may differ in their + missing cells. + + Failure condition: a row is dropped, values diverge, or more features + differ in their missing cells than the known differences explain. """ expected = pd.read_csv(FIXTURE_DIR / "combined_stress_output.tsv", sep="\t", index_col=0) result = harmonize( @@ -721,7 +723,8 @@ def test_combined_stress_vs_r(self): err_msg=f"Combined stress mismatch on {len(match_idx)} NaN-matching features", ) - # Log mismatch count (must be a small fraction) - assert mismatch_count < total / 2, ( - f"Too many NaN position mismatches: {mismatch_count}/{total}" - ) + # 20 of the 50 features differ in their missing cells, from the sort-order + # and unique-removal differences listed in the parity document; more + # would be a new difference. + assert set(result.index) == set(expected.index), "Rows differ from R" + assert mismatch_count <= 20, f"Missing cells differ on {mismatch_count}/{total} features" diff --git a/tests/test_report.py b/tests/test_report.py new file mode 100644 index 0000000..ead7737 --- /dev/null +++ b/tests/test_report.py @@ -0,0 +1,266 @@ +"""Tests for the per-feature correction report of ``harmonize(..., return_report=True)``.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest + +from harmonizepy import HarmonizeResult, harmonize +from harmonizepy.__main__ import main + +_SAMPLES = [f"s{i}" for i in range(1, 10)] +_BATCHES = np.repeat([1, 2, 3], 3) +_DESC = pd.DataFrame({"ID": _SAMPLES, "sample": range(1, 10), "batch": _BATCHES}) + + +def _known_outcomes() -> tuple[pd.DataFrame, dict[str, str]]: + """Return a matrix in which every feature's outcome is known, and those outcomes. + + Batches 1, 2, 3 hold three samples each; ComBat mode 1 needs two values per + batch. + """ + rng = np.random.default_rng(40) + shift = np.array([0.0, 1.0, -1.0])[_BATCHES - 1] + rows: dict[str, np.ndarray] = {} + expected: dict[str, str] = {} + for i in range(20): + rows[f"full_{i}"] = rng.normal(20, 1) + rng.normal(0, 0.3, 9) + shift + expected[f"full_{i}"] = "corrected" + rows["constant"] = np.array([5.0] * 3 + [6.0] * 3 + [7.0] * 3) + expected["constant"] = "raw_zero_variance" + for i in range(3): + values = rng.normal(15, 1) + rng.normal(0, 0.3, 9) + shift + values[_BATCHES == 3] = np.nan + rows[f"first_two_{i}"] = values + expected[f"first_two_{i}"] = "corrected" + alone = rng.normal(12, 1) + rng.normal(0, 0.3, 9) + shift + alone[_BATCHES == 1] = np.nan + rows["alone"] = alone + expected["alone"] = "raw_alone_in_pattern" + for i in range(2): + values = np.full(9, np.nan) + values[_BATCHES == 1] = rng.normal(10, 1, 3) + rows[f"batch_one_{i}"] = values + expected[f"batch_one_{i}"] = "raw_single_batch" + pair_varied = rng.normal(8, 1) + rng.normal(0, 0.3, 9) + shift + pair_varied[_BATCHES == 2] = np.nan + pair_constant = np.array([3.0] * 3 + [np.nan] * 3 + [4.0] * 3) + rows["pair_varied"], rows["pair_constant"] = pair_varied, pair_constant + expected["pair_varied"] = "raw_too_few_features" + expected["pair_constant"] = "raw_zero_variance" + sparse = np.full(9, np.nan) + sparse[[0, 3, 6]] = [1.0, 2.0, 3.0] + rows["sparse"] = sparse + expected["sparse"] = "missing_no_usable_batch" + data = pd.DataFrame(rows, index=_SAMPLES).T + return data, expected + + +class TestReportStatuses: + """Each status, and the columns that describe it.""" + + def test_every_status_matches_the_known_outcome(self) -> None: + """Each feature gets the status its construction implies. + + Failure condition: a feature left raw is reported as corrected, or the + reason given is not the one that applies. + """ + data, expected = _known_outcomes() + _, report = harmonize(data, _DESC, unique_removal=False, return_report=True) + assert report["status"].to_dict() == expected + + def test_batches_used_and_group_size(self) -> None: + """Corrected features list their group's batches; raw features list none. + + Failure condition: the batches or group size do not match the group the + feature was corrected in. + """ + data, _ = _known_outcomes() + _, report = harmonize(data, _DESC, unique_removal=False, return_report=True) + assert report.loc["full_0", "batches_used"] == "1,2,3" + assert report.loc["full_0", "group_size"] == 21 + assert report.loc["first_two_0", "batches_used"] == "1,2" + assert report.loc["first_two_0", "group_size"] == 3 + assert report.loc["constant", "batches_used"] == "" + assert report.loc["sparse", "group_size"] == 0 + + def test_every_feature_appears_once_in_output_order(self) -> None: + """The report has one row per output feature, in the output's order. + + Failure condition: a feature is missing from the report or listed twice. + """ + data, _ = _known_outcomes() + out, report = harmonize(data, _DESC, return_report=True) + assert list(report.index) == list(out.index) + + def test_matrix_is_identical_with_and_without_the_report(self) -> None: + """Asking for the report does not change the corrected matrix. + + Failure condition: the report path corrects differently. + """ + data, _ = _known_outcomes() + plain = harmonize(data, _DESC, sort="sparsity") + result = harmonize(data, _DESC, sort="sparsity", return_report=True) + assert isinstance(result, HarmonizeResult) + pd.testing.assert_frame_equal(result.data, plain) + + def test_cropped_and_repeats_are_recorded(self) -> None: + """A feature moved by unique removal is marked cropped, and removed repeats are counted. + + Failure condition: the report hides that a feature lost the values of the + dropped batch, or that repeats of it were removed. + """ + rows = [ + [1.0 + i, 1.5 + i, 1.2 + i, 2.1 + i, 2.4 + i, 2.2 + i, np.nan, np.nan, np.nan] + for i in range(4) + ] + rows.append([1.0, 1.4, 1.2, 2.0, 2.6, 2.3, 3.1, 3.5, 3.3]) + data = pd.DataFrame(rows, index=[f"p{i}" for i in range(5)], columns=_SAMPLES) + data = pd.concat([data, data.iloc[[0, 0]]]) + _, report = harmonize(data, _DESC, return_report=True) + assert report.loc["p4", "cropped"] + assert report.loc["p4", "batches_used"] == "1,2" + assert not report.loc["p0", "cropped"] + assert report.loc["p0", "repeats_removed"] == 2 + assert report["repeats_removed"].sum() == 2 + + def test_repeats_of_a_feature_without_a_name_are_counted(self) -> None: + """Repeats of a feature whose name is missing are counted like any other. + + Failure condition: the missing name is dropped from the count, so the + report says 0 although two rows were removed. + """ + data, _ = _known_outcomes() + data = data.rename(index={"full_0": np.nan}) + data = pd.concat([data, data.iloc[[0, 0]]]) + _, report = harmonize(data, _DESC, return_report=True) + assert report["repeats_removed"].sum() == 2 + + def test_limma_reports_its_groups(self) -> None: + """With limma, features in a group spanning several batches are corrected. + + Failure condition: limma groups get a ComBat-only status. + """ + data, expected = _known_outcomes() + _, report = harmonize( + data, _DESC, algorithm="limma", unique_removal=False, return_report=True + ) + assert report.loc["full_0", "status"] == "corrected" + assert report.loc["constant", "status"] == "corrected" + assert report.loc["batch_one_0", "status"] == expected["batch_one_0"] + + +class TestReportCommandLine: + """The report written by ``--report``.""" + + def _inputs(self, tmp_path: Path) -> tuple[str, str]: + data, _ = _known_outcomes() + data_path = tmp_path / "data.tsv" + data.to_csv(data_path, sep="\t") + desc_path = tmp_path / "desc.csv" + _DESC.to_csv(desc_path, index=False) + return str(data_path), str(desc_path) + + @pytest.mark.parametrize("suffix", ["tsv", "csv"]) + def test_report_file_matches_the_api(self, tmp_path: Path, suffix: str) -> None: + """``--report`` writes the same table as ``return_report=True``. + + Failure condition: the file and the API disagree on a status or a column. + """ + data_path, desc_path = self._inputs(tmp_path) + report_path = tmp_path / f"report.{suffix}" + main([data_path, desc_path, "--no-log", "-q", "--report", str(report_path)]) + written = pd.read_csv( + report_path, sep="," if suffix == "csv" else "\t", index_col=0, keep_default_na=False + ) + _, report = harmonize(data_path, desc_path, return_report=True) + written["batches_used"] = written["batches_used"].astype(str) + written.index.name = report.index.name + pd.testing.assert_frame_equal(written, report, check_dtype=False) + + def test_report_counts_repeats_in_the_data_file(self, tmp_path: Path) -> None: + """Repeated rows in the data file are counted in the written report. + + Failure condition: the command line removes the repeats before the report + sees them and reports 0. + """ + data, _ = _known_outcomes() + data = pd.concat([data, data.iloc[[0, 0]]]) + data_path = tmp_path / "data.tsv" + data.to_csv(data_path, sep="\t") + desc_path = tmp_path / "desc.csv" + _DESC.to_csv(desc_path, index=False) + report_path = tmp_path / "report.tsv" + main([str(data_path), str(desc_path), "--no-log", "-q", "--report", str(report_path)]) + written = pd.read_csv(report_path, sep="\t", index_col=0, keep_default_na=False) + assert written.loc["full_0", "repeats_removed"] == 2 + assert written["repeats_removed"].sum() == 2 + + def test_parquet_report_keeps_column_types(self, tmp_path: Path) -> None: + """A Parquet report round-trips with its index and column types. + + Failure condition: the boolean or text columns are written as another type. + """ + pytest.importorskip("pyarrow") + data_path, desc_path = self._inputs(tmp_path) + report_path = tmp_path / "report.parquet" + main([data_path, desc_path, "--no-log", "-q", "--report", str(report_path)]) + _, report = harmonize(data_path, desc_path, return_report=True) + pd.testing.assert_frame_equal(pd.read_parquet(report_path), report, check_dtype=False) + assert pd.read_parquet(report_path)["cropped"].dtype == bool + + @pytest.mark.parametrize("target", ["output", "data", "description"]) + def test_report_path_that_would_overwrite_a_file_is_refused( + self, tmp_path: Path, target: str + ) -> None: + """``--report`` naming the output or an input file is a usage error. + + Failure condition: the report overwrites the corrected matrix or an input. + """ + data_path, desc_path = self._inputs(tmp_path) + output = str(tmp_path / "out.tsv") + report = {"output": output, "data": data_path, "description": desc_path}[target] + before = Path(data_path).read_bytes() + with pytest.raises(SystemExit) as excinfo: + main([data_path, desc_path, "--no-log", "-q", "-o", output, "--report", report]) + assert excinfo.value.code == 2 + assert Path(data_path).read_bytes() == before + assert not Path(output).exists() + + def test_empty_report_path_is_refused(self, tmp_path: Path) -> None: + """An empty ``--report`` path is a usage error, not a silent no-op. + + Failure condition: the run succeeds and writes no report. + """ + data_path, desc_path = self._inputs(tmp_path) + with pytest.raises(SystemExit) as excinfo: + main([data_path, desc_path, "--no-log", "-q", "--report", ""]) + assert excinfo.value.code == 2 + + def test_report_from_config_file(self, tmp_path: Path) -> None: + """A ``report`` key in the config file writes the report, and a dry run ignores it. + + Failure condition: the key is rejected, or makes the dry run a usage error. + """ + data_path, desc_path = self._inputs(tmp_path) + report_path = tmp_path / "report.tsv" + config = tmp_path / "run.toml" + config.write_text(f'report = "{report_path.as_posix()}"\n') + main([data_path, desc_path, "--dry-run", "--config", str(config)]) + assert not report_path.exists() + main([data_path, desc_path, "--no-log", "-q", "--config", str(config)]) + assert report_path.is_file() + + def test_dry_run_refuses_report(self, tmp_path: Path) -> None: + """A dry run writes no files, so ``--report`` is a usage error. + + Failure condition: the report option is silently ignored. + """ + data_path, desc_path = self._inputs(tmp_path) + with pytest.raises(SystemExit) as excinfo: + main([data_path, desc_path, "--dry-run", "--report", str(tmp_path / "r.tsv")]) + assert excinfo.value.code == 2 + assert not (tmp_path / "r.tsv").exists() diff --git a/tests/test_smoke.py b/tests/test_smoke.py index d38431a..dc2c421 100644 --- a/tests/test_smoke.py +++ b/tests/test_smoke.py @@ -6,9 +6,9 @@ def test_version_is_defined() -> None: - """Package version string must be ``0.3.2``. + """Package version string must be ``0.4.0``. Failure condition: the version was bumped or a dev install does not match the released version. """ - assert __version__ == "0.3.2" + assert __version__ == "0.4.0" diff --git a/tests/test_sorting.py b/tests/test_sorting.py index a43e0fe..9d9732e 100644 --- a/tests/test_sorting.py +++ b/tests/test_sorting.py @@ -23,6 +23,7 @@ import pandas as pd import pytest +from harmonizepy import harmonize from harmonizepy.blocking import _unique_ordered from harmonizepy.sorting import ( _build_presence_matrix, @@ -66,7 +67,7 @@ def _make_skewed_dataset() -> tuple[pd.DataFrame, np.ndarray]: Batch 3: 5 features present (all NaN in the other 15). With needed_values=2 and n_per_batch=3, presence counts are 20, 10, 5. - Sparsity sort descending → [batch1, batch2, batch3] (most complete first). + Sparsity sort descending gives [batch1, batch2, batch3] (most complete first). """ rng = np.random.default_rng(42) n_features = 20 @@ -395,8 +396,8 @@ def test_typo_raises(self): # --------------------------------------------------------------------------- -class TestHelperFunctions: - """Direct unit tests for internal helper functions.""" +class TestOrderingFunctions: + """The batch orderings and the column permutation, called directly.""" def test_sparsity_order_descending(self): """_sparsity_order returns batches in descending completeness. @@ -468,10 +469,10 @@ def test_seriation_order_permutation(self): np.testing.assert_array_equal(np.sort(order), [0, 1, 2, 3]) def test_seriation_order_anchors_pc1_sign(self): - """_seriation_order anchors the PC1 sign deterministically. + """_seriation_order fixes the PC1 sign and keeps tied batches in input order. - Failure condition: the SVD sign flips and reverses the order for the - same presence matrix across runs or platforms. + Failure condition: the sign flips and reverses the order, or batches 1 + and 2, whose scores are equal, are ordered by rounding noise. """ presence = np.array( [ @@ -484,16 +485,12 @@ def test_seriation_order_anchors_pc1_sign(self): dtype=np.bool_, ) - centered = presence.T.astype(np.float64) - centered -= centered.mean(axis=0) - u, s, _vt = np.linalg.svd(centered, full_matrices=False) - raw_pc1 = u[:, 0] * s[0] - - assert raw_pc1[np.argmax(np.abs(raw_pc1))] < 0 - + # PC1 scores are proportional to (-2, 1, 1): batch 0 has the largest + # magnitude and is made positive, so it moves last, and the tie + # between batches 1 and 2 keeps their input order. order = _seriation_order(presence) - np.testing.assert_array_equal(order, np.argsort(-raw_pc1, kind="stable")) + np.testing.assert_array_equal(order, [1, 2, 0]) def test_column_order_groups_by_batch(self): """_column_order appends indices in the requested batch order. @@ -623,3 +620,60 @@ def test_empty_batch_not_chosen_as_start_when_others_are_not_empty(self): df.iloc[:, 3:6] = np.nan _, sb, _ = sort_batches(df, batch, "jaccard", needed_values=2) assert sb[0] != 2 + + +class TestRowOrderInvariance: + """The batch order, and so the corrected matrix, does not depend on row order.""" + + @staticmethod + def _sparse_frame(seed: int, n_features: int) -> tuple[pd.DataFrame, pd.DataFrame]: + rng = np.random.default_rng(seed) + samples = [f"s{i}" for i in range(10)] + values = rng.normal(10, 2, (n_features, 10)) + values[rng.random(values.shape) < 0.4] = np.nan + data = pd.DataFrame(values, index=[f"f{i}" for i in range(n_features)], columns=samples) + desc = pd.DataFrame( + {"ID": samples, "sample": range(1, 11), "batch": np.repeat(np.arange(1, 6), 2)} + ) + return data, desc + + def test_seriation_with_tied_scores(self) -> None: + """Two row orders of one matrix give the same seriation order. + + The matrix has two batches whose PC1 scores are equal in magnitude and + three near zero, with needed_values=1. + + Failure condition: the sign is chosen by rounding noise, so the order + reverses when the rows are shuffled. + """ + rng = np.random.default_rng(1) + n_features = int(rng.integers(4, 9)) + values = rng.normal(10, 2, (n_features, 10)) + values[rng.random(values.shape) < 0.4] = np.nan + perm = rng.permutation(n_features) + data = pd.DataFrame(values, columns=[f"s{i}" for i in range(10)]) + batches = np.repeat(np.arange(1, 6), 2) + + _, first, _ = sort_batches(data, batches, "seriation", needed_values=1) + _, second, _ = sort_batches(data.iloc[perm], batches, "seriation", needed_values=1) + + np.testing.assert_array_equal(first, second) + + @pytest.mark.parametrize("strategy", ["sparsity", "jaccard", "seriation"]) + def test_harmonize_output_ignores_row_order(self, strategy: str) -> None: + """harmonize() with a sort and block=2 gives the same matrix for shuffled rows. + + Failure condition: the batch order changes with the row order, so the + blocks, and with them the missing cells, change. + """ + for seed in range(25): + data, desc = self._sparse_frame(seed, n_features=8) + perm = np.random.default_rng(seed + 100).permutation(len(data)) + settings = {"sort": strategy, "block": 2, "combat_mode": 4, "unique_removal": False} + + first = harmonize(data, desc, **settings) + second = harmonize(data.iloc[perm], desc, **settings).loc[data.index] + + np.testing.assert_array_equal(first.isna().to_numpy(), second.isna().to_numpy()) + # Rows are fitted in a different order, so values may differ by rounding. + np.testing.assert_allclose(first.to_numpy(), second.to_numpy(), rtol=1e-10, atol=1e-10) diff --git a/tests/test_splitting.py b/tests/test_splitting.py index 933ba6f..4c3c105 100644 --- a/tests/test_splitting.py +++ b/tests/test_splitting.py @@ -6,13 +6,15 @@ from __future__ import annotations -from typing import Any, cast +from typing import cast import numpy as np import pandas as pd +import pytest from harmonizepy.affiliation import build_affiliation_list from harmonizepy.combat import combat as _combat +from harmonizepy.limma_wrapper import remove_batch_effect from harmonizepy.splitting import splitting _Affil = list[tuple[int, ...]] @@ -103,36 +105,21 @@ def test_single_feature_group_copies_raw(self) -> None: assert result.shape == data.shape -class TestSplittingNanAudit: - def test_per_cell_nan_passed_to_combat(self, monkeypatch: Any) -> None: - """Sub-DataFrames with per-cell NaN are passed to combat, which handles it. +class TestPerCellMissingValues: + def test_group_with_missing_cells_equals_combat_on_its_sub_matrix(self) -> None: + """A group with missing cells is corrected exactly as ``combat()`` corrects its sub-matrix. - Failure condition: splitting tries to drop columns or otherwise - prevent NaN from reaching the engine. - - This matches R HarmonizR behavior: per-cell NaN within qualifying - blocks reaches sva::ComBat, which uses Beta.NA per-feature. + Failure condition: splitting drops columns or rows with missing cells + before the engine sees them, so the result differs from the engine's. """ - import harmonizepy.splitting as split_mod - - called_with_nan = [False] - - def tracking(data: np.ndarray, batch: np.ndarray, **kwargs: Any) -> np.ndarray: - if np.isnan(data).any(): - called_with_nan[0] = True - return _combat(data, batch, **kwargs) - - monkeypatch.setattr(split_mod, "combat", tracking) - data = _make_data(6, 6) - data.iloc[0, 0] = np.nan # per-cell NaN, still qualifies for batch 1 - data.iloc[0, 3] = np.nan # per-cell NaN, still qualifies for batch 2 + data.iloc[0, 0] = np.nan + data.iloc[0, 3] = np.nan batch = np.array([1, 1, 1, 2, 2, 2]) - block = batch.copy() - affil = build_affiliation_list(data, batch, block, needed_values=2) - # Feature 0 still qualifies (2 non-NaN per batch) - splitting(affil, data, batch, block, algorithm="ComBat", combat_mode=2) - assert called_with_nan[0], "Engine should have received NaN data" + affil = build_affiliation_list(data, batch, batch, needed_values=2) + out = splitting(affil, data, batch, batch, algorithm="ComBat", combat_mode=2) + expected = _combat(data.to_numpy(), batch, mean_only=True) + np.testing.assert_array_equal(out.to_numpy(), expected) def test_per_cell_nan_handled_correctly(self) -> None: """Per-cell NaN is preserved in original positions; other cells adjusted. @@ -185,3 +172,83 @@ def test_partial_missing_produces_multiple_groups(self) -> None: assert all(a == (1, 2) for a in affil[2:]) result = splitting(affil, data, batch, block, algorithm="ComBat", combat_mode=2) assert result.shape == data.shape + + +class TestSingleFeatureGroupRaw: + """A feature alone in its batch pattern keeps its raw values.""" + + @pytest.mark.parametrize("algorithm", ["ComBat", "limma"]) + def test_single_feature_group_keeps_raw_values(self, algorithm: str) -> None: + """The one-feature group returns exactly its input values for both engines. + + Failure condition: the feature is corrected, or set to missing, instead of + keeping its raw values. + """ + from harmonizepy.splitting import splitting + + rng = np.random.default_rng(11) + data = pd.DataFrame(rng.normal(10, 1, (3, 6)), columns=list("abcdef")) + # A missing cell checks that the row is copied with the cell still missing. + data.iloc[2, 0] = np.nan + batch = np.array([1, 1, 2, 2, 3, 3]) + affil = [(1, 2), (1, 2), (1, 2, 3)] + out = splitting(affil, data, batch, batch, algorithm=algorithm, combat_mode=1) + # Exact equality: raw values are copied, so no tolerance applies. + np.testing.assert_array_equal(out.iloc[2].to_numpy(), data.iloc[2].to_numpy()) + + +class TestSplittingArguments: + """Unknown engines and modes are rejected before any group is corrected.""" + + @pytest.mark.parametrize( + "algorithm, mode, message", + [ + ("bogus", 1, "algorithm must be"), + ("ComBat", 9, "combat_mode must be"), + ("ComBat", [2], "combat_mode must be"), + ], + ) + def test_unknown_algorithm_or_mode_raises( + self, algorithm: str, mode: object, message: str + ) -> None: + """An unknown algorithm or ComBat mode raises ``ValueError``. + + Failure condition: an unknown algorithm silently runs ComBat, or an unknown + mode raises a bare ``KeyError``. + """ + data = pd.DataFrame(np.ones((2, 4)), columns=list("abcd")) + batch = np.array([1, 1, 2, 2]) + with pytest.raises(ValueError, match=message): + splitting([(1, 2), (1, 2)], data, batch, batch, algorithm=algorithm, combat_mode=mode) + + +class TestSpanningGroup: + """A group that covers every row and column is read without a copy.""" + + @pytest.mark.parametrize("algorithm", ["ComBat", "limma"]) + @pytest.mark.parametrize("with_missing", [False, True]) + def test_output_equals_engine_and_input_unchanged( + self, algorithm: str, with_missing: bool + ) -> None: + """The spanning group gives the engine's output and leaves the caller's array as it was. + + Failure condition: the engine writes into the shared array, or the in-place + read changes the result. + """ + rng = np.random.default_rng(18) + values = rng.normal(10, 1, (8, 6)) + np.repeat([0.0, 1.0, 2.0], 2) + if with_missing: + values[2, 0] = np.nan + values[5, 3] = np.nan + data = pd.DataFrame(values, columns=list("abcdef")) + data_np = data.to_numpy(dtype=np.float64) + before = data_np.copy() + batch = np.array([1, 1, 2, 2, 3, 3]) + out = splitting( + [(1, 2, 3)] * 8, data, batch, batch, algorithm=algorithm, combat_mode=1, data_np=data_np + ) + np.testing.assert_array_equal(data_np, before) + expected = ( + _combat(before, batch) if algorithm == "ComBat" else remove_batch_effect(before, batch) + ) + np.testing.assert_array_equal(out.to_numpy(), expected) diff --git a/tests/test_unique_removal.py b/tests/test_unique_removal.py index 3e82f5f..8df44bc 100644 --- a/tests/test_unique_removal.py +++ b/tests/test_unique_removal.py @@ -2,16 +2,16 @@ Sections -------- -1. TestSingletonRescue: singletons are cropped to nearest shared pattern +1. TestSingletonRescue: singletons move into another feature's pattern 2. TestNonSingletonUnchanged: non-singleton and empty tuples are not modified 3. TestMinimalCropping: fewest batches removed (greedy largest-first) 4. TestEdgeCases: all unique, single feature, already shared -5. TestHelperFunctions: _find_best_crop +5. TestTieOrder, TestOneBatchTargets, TestWideTargets: the target rule """ from __future__ import annotations -from harmonizepy.affiliation import _find_best_crop, remove_unique_combinations +from harmonizepy.affiliation import remove_unique_combinations # --------------------------------------------------------------------------- # 1. TestSingletonRescue @@ -20,7 +20,7 @@ class TestSingletonRescue: def test_basic_singleton_cropped_to_shared_pattern(self): - """Singleton is cropped to the nearest shared pattern. + """Singleton is cropped to the longest pattern within its own. Failure condition: a singleton feature is not rescued or is cropped to an incorrect subset. @@ -214,7 +214,7 @@ def test_all_empty_affiliations(self): assert result == [(), (), ()] def test_large_singleton(self): - """A singleton with many blocks is cropped to the largest shared subset. + """A singleton with many blocks is cropped to the longest subset another feature holds. Failure condition: a singleton with 6 blocks is cropped too aggressively. @@ -226,44 +226,161 @@ def test_large_singleton(self): # --------------------------------------------------------------------------- -# 5. TestHelperFunctions -# --------------------------------------------------------------------------- +# 5. TestFindBestCrop +class TestTieOrder: + """Equally long candidates are chosen by a rule that ignores row order.""" + + _AFFILIATIONS = ( + (2, 3), + (2, 3), + (1, 2), + (1, 2), + (3, 6), + (3, 6), + (2, 4, 5, 6), + (2, 4, 5, 6), + (1, 2, 3, 5), + (2, 3, 5, 6), + (1, 2, 4, 6), + ) + + def test_choice_is_the_same_in_every_row_order(self) -> None: + """Every shuffle of the rows moves each feature to the same affiliation. + + Failure condition: the choice follows the iteration order of a set built + from the rows, so it flips between ``(2, 3)`` and ``(1, 2)``. + """ + import random + + expected = remove_unique_combinations(list(self._AFFILIATIONS)) + rng = random.Random(0) + for _ in range(200): + order = list(range(len(self._AFFILIATIONS))) + rng.shuffle(order) + result = remove_unique_combinations([self._AFFILIATIONS[i] for i in order]) + assert [result[order.index(i)] for i in range(len(order))] == expected + + def test_smallest_tuple_breaks_a_tie_of_equal_groups(self) -> None: + """Between candidates shared by equally many features, the smaller tuple wins. + + Failure condition: the tie goes to ``(2, 3)`` in some runs. + """ + assert remove_unique_combinations(list(self._AFFILIATIONS))[8] == (1, 2) + + def test_larger_group_wins_a_tie_of_length(self) -> None: + """Among equally long candidates, the one more features share wins. + + Failure condition: the smaller tuple wins although its group is smaller. + """ + affiliations = [(1, 2), (1, 2), (2, 3), (2, 3), (2, 3), (1, 2, 3)] + assert remove_unique_combinations(affiliations)[5] == (2, 3) + + def test_harmonize_output_does_not_depend_on_row_order(self) -> None: + """Shuffling the rows of the matrix gives the same corrected values per feature. + + Failure condition: a tie resolved by row order puts a feature in another + group, and its corrected values change. + """ + import numpy as np + import pandas as pd + + from harmonizepy import harmonize + + rng = np.random.default_rng(3) + batch = np.repeat(np.arange(1, 7), 2) + samples = [f"s{i}" for i in range(12)] + rows = {} + for k, affiliation in enumerate(self._AFFILIATIONS): + values = rng.normal(20, 1) + rng.normal(0, 0.3, 12) + 0.5 * batch + values[~np.isin(batch, affiliation)] = np.nan + rows[f"f{k}"] = values + data = pd.DataFrame(rows, index=samples).T + desc = pd.DataFrame({"ID": samples, "sample": range(1, 13), "batch": batch}) + expected = harmonize(data, desc) + for seed in range(10): + shuffled = harmonize(data.sample(frac=1.0, random_state=seed), desc) + pd.testing.assert_frame_equal(shuffled.loc[expected.index], expected, rtol=1e-12) + + +class TestOneBatchTargets: + """A crop never lands in an affiliation that spans a single batch.""" + + def test_one_batch_target_is_refused(self) -> None: + """A feature is not moved into a pattern of one batch. + + Failure condition: the feature loses its other batches and is still left raw. + """ + assert remove_unique_combinations([(2,), (2,), (2, 3)]) == [(2,), (2,), (2, 3)] + + def test_one_block_of_two_batches_is_a_target(self) -> None: + """With blocking, a single block that holds two batches is still a target. + + Failure condition: blocks are counted as batches and the crop is refused. + """ + result = remove_unique_combinations([(2,), (2,), (2, 3)], {2: 2, 3: 1}) + assert result == [(2,), (2,), (2,)] + + def test_harmonize_keeps_the_feature_whole(self) -> None: + """Proteins A and B measured in batch 2 only, C in batches 2 and 3: C keeps + its batch 3 values and is reported alone in its pattern. + + Failure condition: C is cropped to batch 2, its batch 3 values are emptied, + and it still comes out raw. + """ + import numpy as np + import pandas as pd + + from harmonizepy import harmonize + + samples = [f"s{i}" for i in range(9)] + batch = np.repeat([1, 2, 3], 3) + rng = np.random.default_rng(5) + data = pd.DataFrame(np.nan, index=["A", "B", "C"], columns=samples) + data.loc[["A", "B"], np.array(samples)[batch == 2]] = rng.normal(10, 1, (2, 3)) + data.loc["C", np.array(samples)[batch >= 2]] = rng.normal(12, 1, 6) + desc = pd.DataFrame({"ID": samples, "sample": range(1, 10), "batch": batch}) + out, report = harmonize(data, desc, return_report=True) + pd.testing.assert_series_equal(out.loc["C"], data.loc["C"]) + assert report.loc["C", "status"] == "raw_alone_in_pattern" + assert not report.loc["C", "cropped"] + +class TestWideTargets: + """A feature may move into the pattern of a single other feature, as in HarmonizR.""" -class TestFindBestCrop: - def test_finds_largest_matching_subset(self): - """Returns the largest matching subset of the input set. + def test_harmonizr_example(self) -> None: + """``(1,2,3,4), (1,2), (5,6), (5,6)``: the first feature joins the second. - Failure condition: a non-maximal subset is returned. + Failure condition: the first feature stays alone because ``(1, 2)`` is held + by one feature only (the narrower rule). """ - non_unique: set[tuple[int, ...]] = {(1, 2, 3), (1, 2)} - best = _find_best_crop(frozenset({1, 2, 3, 4}), non_unique) - assert best == (1, 2, 3) + result = remove_unique_combinations([(1, 2, 3, 4), (1, 2), (5, 6), (5, 6)]) + assert result == [(1, 2), (1, 2), (5, 6), (5, 6)] - def test_returns_none_when_no_match(self): - """Returns None when no subset matches. + def test_target_feature_keeps_its_pattern(self) -> None: + """A unique feature used as a target is not moved itself. - Failure condition: a non-existent match is returned. + Failure condition: the target moves on to a smaller pattern and the pair breaks. """ - non_unique: set[tuple[int, ...]] = {(5, 6)} - best = _find_best_crop(frozenset({1, 2}), non_unique) - assert best is None + result = remove_unique_combinations([(1, 2, 3, 4), (1, 2, 3), (1, 2), (1, 2)]) + assert result == [(1, 2, 3), (1, 2, 3), (1, 2), (1, 2)] - def test_single_element_subset(self): - """A single-element subset can be a valid match. + def test_feature_without_target_keeps_its_values(self) -> None: + """A feature with no subset keeps its affiliation; it is not emptied. - Failure condition: single-element subsets are skipped. + Failure condition: the affiliation becomes empty, so the feature comes out + missing, as HarmonizR returns it. """ - non_unique: set[tuple[int, ...]] = {(3,)} - best = _find_best_crop(frozenset({1, 2, 3}), non_unique) - assert best == (3,) + result = remove_unique_combinations([(1, 2), (3, 4), (3, 4)]) + assert result == [(1, 2), (3, 4), (3, 4)] - def test_exact_match_not_searched(self): - """Only strict subsets are searched, not the input itself. + def test_longest_affiliation_is_taken_first(self) -> None: + """Features are processed longest affiliation first, whatever the row order. - Failure condition: the input itself is returned when it - is already a non-unique pattern. + Failure condition: a shorter unique affiliation is processed first, moves + into the longer one's target, and the longer one is left alone. """ - non_unique: set[tuple[int, ...]] = {(1, 2, 3), (1, 2)} - best = _find_best_crop(frozenset({1, 2, 3}), non_unique) - assert best == (1, 2) + rows = [(1, 2, 3), (1, 2, 3, 4), (1, 2), (1, 2)] + expected = [(1, 2, 3), (1, 2, 3), (1, 2), (1, 2)] + assert remove_unique_combinations(rows) == expected + assert remove_unique_combinations(rows[::-1]) == expected[::-1] diff --git a/tests/test_validation.py b/tests/test_validation.py index d050dbc..3d6fe09 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -6,16 +6,24 @@ from __future__ import annotations +import warnings +from typing import ClassVar + import numpy as np import pandas as pd import pytest +from harmonizepy.core import harmonize from harmonizepy.validation import ( - validate_combat_input, + InputScaleWarning, + check_input_scale, + sample_batch_map, + validate_combat_mode, validate_data_matrix, validate_description, + validate_engine_input, validate_harmonize_args, - validate_limma_input, + validate_ref_batch, ) # --------------------------------------------------------------------------- @@ -59,6 +67,17 @@ def test_too_few_columns(self) -> None: with pytest.raises(ValueError, match="at least 2 sample columns"): validate_data_matrix(df) + def test_infinite_value_raises_naming_the_feature(self) -> None: + """An infinite value is rejected, and the message names its feature. + + Failure condition: the matrix passes and the engine turns every value missing. + """ + df = pd.DataFrame({"s1": [1.0, -np.inf], "s2": [2.0, 3.0]}, index=["p1", "p2"]) + with pytest.raises( + ValueError, match=r"infinite values in 1 feature\(s\) \(first: \['p2'\]\)" + ): + validate_data_matrix(df) + # --------------------------------------------------------------------------- # validate_description @@ -98,112 +117,49 @@ def test_too_few_columns(self) -> None: # --------------------------------------------------------------------------- -# validate_combat_input +# validate_engine_input # --------------------------------------------------------------------------- -class TestValidateCombatInput: - def test_valid(self) -> None: - """Valid combat input passes without error. +class TestValidateEngineInput: + """The matrix and label checks shared by ``combat()`` and ``remove_batch_effect()``.""" + + def test_valid_input_passes(self) -> None: + """A 2-D matrix with one label per sample passes. Failure condition: a valid array-batch pair is rejected. """ - data = np.ones((5, 4), dtype=np.float64) - batch = np.array([0, 0, 1, 1], dtype=np.intp) - validate_combat_input(data, batch) # no error + validate_engine_input(np.ones((5, 4)), np.array([0, 0, 1, 1])) - def test_contains_nan_passes(self) -> None: - """NaN in data does NOT raise ValueError. + def test_missing_cells_pass(self) -> None: + """Missing cells pass; the engines fit each feature on its observed cells. - Failure condition: the validator rejects NaN input - (per-cell NaN is handled by combat() via row-dropping, - matching R sva::ComBat's na.omit). + Failure condition: the validator rejects a matrix with a missing cell. """ - data = np.array([[1.0, np.nan], [3.0, 4.0]]) - batch = np.array([0, 1], dtype=np.intp) - validate_combat_input(data, batch) # should not raise + validate_engine_input(np.array([[1.0, np.nan], [3.0, 4.0]]), np.array([0, 1])) - def test_no_min_feature_check(self) -> None: - """validate_combat_input does NOT reject n_features < 2. + def test_single_feature_passes(self) -> None: + """A single feature passes; the engines decide how to handle it. - Failure condition: the validator rejects input with < 2 features - (combat() handles this internally via NaN row dropping or - pass-through). - - Per-cell NaN may reduce clean features below 2; the validator - must let the engine decide. + Failure condition: the validator rejects a one-row matrix. """ - data = np.ones((1, 4), dtype=np.float64) - batch = np.array([0, 0, 1, 1], dtype=np.intp) - validate_combat_input(data, batch) # should not raise + validate_engine_input(np.ones((1, 4)), np.array([0, 0, 1, 1])) - def test_one_dimensional(self) -> None: - """1-D input raises ValueError. + def test_one_dimensional_raises(self) -> None: + """A 1-D array raises ``ValueError``. Failure condition: a flat array is not rejected as 2-D required. """ - data = np.array([1.0, 2.0, 3.0, 4.0]) - batch = np.array([0, 0, 1, 1], dtype=np.intp) with pytest.raises(ValueError, match="2-D"): - validate_combat_input(data, batch) + validate_engine_input(np.array([1.0, 2.0, 3.0, 4.0]), np.array([0, 0, 1, 1])) - def test_batch_length_mismatch(self) -> None: - """Mismatched batch length raises ValueError. + def test_batch_length_mismatch_raises(self) -> None: + """A batch with the wrong number of labels raises ``ValueError``. - Failure condition: batch labels do not match the sample dimension - and the mismatch is not detected. + Failure condition: the mismatch between labels and samples is not detected. """ - data = np.ones((3, 5), dtype=np.float64) - batch = np.array([0, 0, 1], dtype=np.intp) with pytest.raises(ValueError, match="batch length"): - validate_combat_input(data, batch) - - -# --------------------------------------------------------------------------- -# validate_limma_input -# --------------------------------------------------------------------------- - - -class TestValidateLimmaInput: - def test_valid(self) -> None: - """Valid limma input passes without error. - - Failure condition: a valid array-batch pair is rejected. - """ - data = np.ones((5, 4), dtype=np.float64) - batch = np.array([0, 0, 1, 1]) - validate_limma_input(data, batch) # no error - - def test_contains_nan_passes(self) -> None: - """NaN in data does NOT raise ValueError. - - Failure condition: the validator rejects NaN input - (per-cell NaN is handled by the engine via row-dropping, - matching R sva::ComBat's na.omit). - """ - data = np.array([[1.0, np.nan], [3.0, 4.0]]) - batch = np.array([0, 1]) - validate_limma_input(data, batch) # should not raise - - def test_one_dimensional(self) -> None: - """1-D input raises ValueError. - - Failure condition: a flat array is not rejected. - """ - data = np.array([1.0, 2.0, 3.0]) - batch = np.array([0, 1, 1]) - with pytest.raises(ValueError, match="2-D"): - validate_limma_input(data, batch) - - def test_batch_length_mismatch(self) -> None: - """Mismatched batch length raises ValueError. - - Failure condition: batch-sample mismatch is not detected. - """ - data = np.ones((3, 5), dtype=np.float64) - batch = np.array([0, 0, 1]) - with pytest.raises(ValueError, match="batch length"): - validate_limma_input(data, batch) + validate_engine_input(np.ones((3, 5)), np.array([0, 0, 1])) # --------------------------------------------------------------------------- @@ -243,6 +199,22 @@ def test_needed_values_zero(self) -> None: with pytest.raises(ValueError, match="needed_values"): validate_harmonize_args("ComBat", 1, 0) + @pytest.mark.parametrize("value", [2.5, 2.0, True, "2"]) + def test_needed_values_must_be_a_whole_number(self, value: object) -> None: + """A float, a boolean, or a string is rejected as needed_values. + + Failure condition: 2.5 acts as 3 and ``True`` as 1 without a message. + """ + with pytest.raises(ValueError, match="needed_values must be a whole number"): + validate_harmonize_args("ComBat", 1, value) # type: ignore[arg-type] + + def test_needed_values_accepts_numpy_integers(self) -> None: + """A NumPy integer is a valid needed_values. + + Failure condition: an integer read from an array is rejected. + """ + validate_harmonize_args("ComBat", 1, np.int64(2)) # type: ignore[arg-type] + def test_invalid_sort_strategy(self) -> None: """Unknown sort strategy raises ValueError. @@ -290,3 +262,272 @@ def test_valid_block_size(self) -> None: """ validate_harmonize_args("ComBat", 1, 2, block_size=2, n_batches=5) validate_harmonize_args("ComBat", 1, 2, block_size=4, n_batches=5) + + +class TestDescriptionColumns: + """One rule finds the ID and batch columns for validation and for the batch map.""" + + _DATA: ClassVar[pd.DataFrame] = pd.DataFrame(np.zeros((1, 4)), columns=["s1", "s2", "s3", "s4"]) + + def test_id_by_name_without_batch_name_uses_third_column(self) -> None: + """With an ``ID`` column but no ``batch`` column, the third column holds the labels. + + Failure condition: validation finds IDs by name while the map reads them by + position, so samples get another sample's batch. + """ + desc = pd.DataFrame( + {"sample": [4, 3, 2, 1], "ID": ["s1", "s2", "s3", "s4"], "group": [1, 1, 2, 2]} + ) + validate_description(desc, self._DATA) + assert sample_batch_map(desc) == {"s1": 1, "s2": 1, "s3": 2, "s4": 2} + + def test_id_in_third_column_without_batch_name_raises(self) -> None: + """If the ID column is also the third column, the batch column cannot be found. + + Failure condition: the IDs are read as batch labels. + """ + desc = pd.DataFrame({"a": [1, 2, 3, 4], "b": [1, 1, 2, 2], "ID": ["s1", "s2", "s3", "s4"]}) + with pytest.raises(ValueError, match="Name the batch column 'batch'"): + validate_description(desc, self._DATA) + + @pytest.mark.parametrize("labels", [[1, 1, 1.5, 2], [1, 1, "A", 2], [1, 1, None, 2]]) + def test_non_whole_batch_labels_raise(self, labels: list[object]) -> None: + """Fractions, text, and blanks in the batch column are rejected by name. + + Failure condition: 1.5 is truncated to 1, or text fails later with an error + that names no column. + """ + desc = pd.DataFrame( + {"ID": ["s1", "s2", "s3", "s4"], "sample": [1, 2, 3, 4], "batch": labels} + ) + with pytest.raises(ValueError, match="column 'batch' must be whole numbers"): + validate_description(desc, self._DATA) + + def test_whole_float_labels_accepted(self) -> None: + """Labels written as 1.0 and 2.0 are accepted as batches 1 and 2. + + Failure condition: whole numbers stored as floats are rejected. + """ + desc = pd.DataFrame( + {"ID": ["s1", "s2", "s3", "s4"], "sample": [1, 2, 3, 4], "batch": [1.0, 1.0, 2.0, 2.0]} + ) + validate_description(desc, self._DATA) + assert sample_batch_map(desc) == {"s1": 1, "s2": 1, "s3": 2, "s4": 2} + + def test_repeated_sample_id_raises(self) -> None: + """A sample listed twice is rejected. + + Failure condition: the later row silently wins. + """ + desc = pd.DataFrame( + { + "ID": ["s1", "s1", "s2", "s3", "s4"], + "sample": [1, 2, 3, 4, 5], + "batch": [1, 2, 1, 2, 2], + } + ) + with pytest.raises(ValueError, match="listed more than once"): + validate_description(desc, self._DATA) + + def test_batch_first_without_id_name_raises_naming_the_id_column(self) -> None: + """A first column named ``batch`` with no ``ID`` column is reported as a missing ID column. + + Failure condition: the message blames the third column, which is unrelated. + """ + desc = pd.DataFrame( + {"batch": [1, 1, 2, 2], "sample_id": ["s1", "s2", "s3", "s4"], "x": [0, 0, 0, 0]} + ) + with pytest.raises(ValueError, match="the ID column cannot be found"): + validate_description(desc, self._DATA) + + def test_large_integer_labels_stay_distinct(self) -> None: + """Integer labels above 2**53 keep their exact values. + + Failure condition: the labels pass through float64 and two batches merge. + """ + big = 2**53 + desc = pd.DataFrame( + { + "ID": ["s1", "s2", "s3", "s4"], + "sample": [1, 2, 3, 4], + "batch": [big + 1, big + 1, big, 3], + } + ) + validate_description(desc, self._DATA) + assert sample_batch_map(desc) == {"s1": big + 1, "s2": big + 1, "s3": big, "s4": 3} + + def test_float_label_beyond_exact_range_raises(self) -> None: + """A float label at or beyond 2**53 is rejected, since it may already be rounded. + + Failure condition: 1e19 is cast to a wrapped-around integer. + """ + desc = pd.DataFrame( + { + "ID": ["s1", "s2", "s3", "s4"], + "sample": [1, 2, 3, 4], + "batch": [1e19, 1e19, 2.0, 2.0], + } + ) + with pytest.raises(ValueError, match="must be whole numbers"): + validate_description(desc, self._DATA) + + def test_map_rejects_repeated_ids(self) -> None: + """``sample_batch_map`` rejects a repeated sample ID when called on its own. + + Failure condition: the later row silently wins. + """ + desc = pd.DataFrame({"ID": ["s1", "s1", "s2"], "sample": [1, 2, 3], "batch": [1, 2, 1]}) + with pytest.raises(ValueError, match="listed more than once"): + sample_batch_map(desc) + + +def test_duplicate_sample_names_raise() -> None: + """A repeated sample name in the data matrix is rejected. + + Failure condition: the matrix passes, and a sorted run fails with a shape error + or an unsorted run silently maps both columns to one description row. + """ + df = pd.DataFrame([[1.0, 2.0, 3.0]], columns=["s1", "s1", "s2"]) + with pytest.raises(ValueError, match="duplicate sample names"): + validate_data_matrix(df) + + +class TestSharedValidators: + """Checks used by several entry points.""" + + @pytest.mark.parametrize("mode", [1, 4, np.int64(3), np.int32(2)]) + def test_integer_modes_accepted(self, mode: object) -> None: + """Python and NumPy integers from 1 to 4 are ComBat modes. + + Failure condition: a NumPy integer from a config file or array is rejected. + """ + validate_combat_mode(mode) + + @pytest.mark.parametrize("mode", [True, np.True_, 1.0, np.float32(4.0), "1", [1], 0, 5]) + def test_other_modes_rejected(self, mode: object) -> None: + """Booleans, floats, strings, lists, and integers outside 1 to 4 are rejected. + + Failure condition: ``True`` or ``1.0`` is accepted because it compares equal to 1. + """ + with pytest.raises(ValueError, match="combat_mode must be 1, 2, 3, or 4"): + validate_combat_mode(mode) + + def test_harmonize_config_rejects_boolean_mode(self) -> None: + """``HarmonizeConfig`` applies the same mode rule. + + Failure condition: the config accepts a mode the engine wrapper rejects. + """ + from harmonizepy import HarmonizeConfig + + with pytest.raises(ValueError, match="combat_mode"): + HarmonizeConfig(combat_mode=True) + + def test_reference_batch_must_exist_and_have_two_samples(self) -> None: + """A reference batch must be a label with at least two samples; ``None`` passes. + + Failure condition: an unknown or single-sample reference batch is accepted. + """ + batch = np.array([0, 0, 1, 2, 2]) + validate_ref_batch(batch, None) + validate_ref_batch(batch, 0) + with pytest.raises(ValueError, match="not found"): + validate_ref_batch(batch, 9) + with pytest.raises(ValueError, match="single sample"): + validate_ref_batch(batch, 1) + + +class TestInputScale: + """The heuristic warning for data that do not look log-transformed.""" + + def test_raw_intensities_warn(self) -> None: + """Non-negative values with a 95th percentile above 100 warn, naming the log transform. + + Failure condition: raw intensities are corrected without any notice. + """ + values = np.random.default_rng(25).lognormal(12, 2, (200, 12)) + with pytest.warns(InputScaleWarning, match=r"untransformed.*log2.*heuristic"): + check_input_scale(values) + + def test_raw_counts_warn(self) -> None: + """Negative-binomial counts with a median near 200 warn. + + Failure condition: realistic raw counts stay below the threshold. + """ + values = np.random.default_rng(29).negative_binomial(5, 5 / 205, (500, 20)).astype(float) + with pytest.warns(InputScaleWarning, match="untransformed"): + check_input_scale(values) + + def test_raw_columns_found_whatever_their_positions(self) -> None: + """Raw values in every other column are found; the sample keeps every column. + + Failure condition: a stride over the flattened matrix samples even columns + only and misses the raw ones. + """ + rng = np.random.default_rng(30) + values = rng.normal(20, 3, (4000, 2000)) + values[:, 1::2] = rng.lognormal(12, 1, (4000, 1000)) + with pytest.warns(InputScaleWarning, match="untransformed"): + check_input_scale(values) + + def test_proportions_warn(self) -> None: + """Values between 0 and 1 warn, naming the M-value transform. + + Failure condition: methylation beta values are corrected as if unbounded. + """ + values = np.random.default_rng(26).beta(2, 5, (200, 12)) + with pytest.warns(InputScaleWarning, match=r"proportions.*M-values.*heuristic"): + check_input_scale(values) + + @pytest.mark.parametrize( + "values", + [ + np.random.default_rng(27).normal(20, 2, (200, 12)), + np.random.default_rng(27).normal(-2, 2, (200, 12)), + np.random.default_rng(27).normal(0, 2, (200, 12)), + np.random.default_rng(27).integers(0, 2, (200, 12)).astype(float), + np.zeros((20, 6)), + ], + ids=["log2-intensity", "negative", "zero-centred", "binary", "constant"], + ) + def test_log_scale_binary_and_constant_values_are_quiet(self, values: np.ndarray) -> None: + """Log-scale values, binary data, and a constant matrix do not warn. + + Failure condition: ordinary log2 intensities, log ratios, or 0/1 data trigger + the warning. + """ + values = values.copy() + values[0, 0] = np.nan + with warnings.catch_warnings(): + warnings.simplefilter("error", InputScaleWarning) + check_input_scale(values) + + def test_harmonize_warns_once_at_the_callers_line_and_can_be_silenced(self) -> None: + """``harmonize()`` warns once, pointing at the caller, and the category silences it. + + Failure condition: the warning repeats per group, points into the package, + or is not silenced by its category. + """ + rng = np.random.default_rng(28) + samples = [f"s{i}" for i in range(1, 7)] + data = pd.DataFrame(rng.lognormal(12, 1, (20, 6)), columns=samples) + desc = pd.DataFrame({"ID": samples, "sample": range(1, 7), "batch": [1, 1, 1, 2, 2, 2]}) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + harmonize(data, desc) + scale_warnings = [w for w in caught if issubclass(w.category, InputScaleWarning)] + assert len(scale_warnings) == 1 + assert scale_warnings[0].filename == __file__ + with warnings.catch_warnings(): + warnings.simplefilter("error") + warnings.filterwarnings("ignore", category=InputScaleWarning) + harmonize(data, desc) + + def test_warning_class_is_exported(self) -> None: + """``InputScaleWarning`` is part of the package's public names. + + Failure condition: users cannot import the category to silence it. + """ + import harmonizepy + + assert harmonizepy.InputScaleWarning is InputScaleWarning + assert "InputScaleWarning" in harmonizepy.__all__ diff --git a/tests/test_wiki_check.py b/tests/test_wiki_check.py index ddcd317..a99371d 100644 --- a/tests/test_wiki_check.py +++ b/tests/test_wiki_check.py @@ -36,7 +36,7 @@ def test_current_wiki_passes() -> None: result = _run_validator(_REPOSITORY_ROOT / "wiki") assert result.returncode == 0, result.stderr - assert "validated 12 wiki pages" in result.stdout + assert "validated 21 wiki pages" in result.stdout def test_resolves_space_and_hyphen_page_names(tmp_path: Path) -> None: @@ -63,12 +63,12 @@ def test_rejects_missing_page_and_repository_style_link(tmp_path: Path) -> None: assert "repository-style .md wiki link: Home.md" in result.stderr -@pytest.mark.parametrize("bad_entry", ["notes.txt", "assets"]) +@pytest.mark.parametrize("bad_entry", ["notes.txt", "images"]) def test_rejects_non_markdown_top_level_entries(tmp_path: Path, bad_entry: str) -> None: wiki_dir = tmp_path / "wiki" _write_pages(wiki_dir) bad_path = wiki_dir / bad_entry - if bad_entry == "assets": + if bad_entry == "images": bad_path.mkdir() else: bad_path.write_text("not a wiki page\n", encoding="utf-8") @@ -77,3 +77,50 @@ def test_rejects_non_markdown_top_level_entries(tmp_path: Path, bad_entry: str) assert result.returncode == 1 assert "regular top-level files" in result.stderr or "Markdown pages only" in result.stderr + + +_PICTURE = """ + + A flow. + +""" + + +def _write_assets(wiki_dir: Path, *names: str) -> None: + asset_dir = wiki_dir / "assets" + asset_dir.mkdir() + for name in names: + (asset_dir / name).write_bytes(b"\x89PNG\r\n\x1a\n") + + +def test_accepts_png_images_in_assets(tmp_path: Path) -> None: + wiki_dir = tmp_path / "wiki" + _write_pages(wiki_dir, **{"Flow.md": _PICTURE, "Plot.md": "![A plot](assets/flow-light.png)\n"}) + _write_assets(wiki_dir, "flow-dark.png", "flow-light.png") + + result = _run_validator(wiki_dir) + + assert result.returncode == 0, result.stderr + + +def test_rejects_missing_image(tmp_path: Path) -> None: + wiki_dir = tmp_path / "wiki" + _write_pages(wiki_dir, **{"Flow.md": _PICTURE}) + _write_assets(wiki_dir, "flow-light.png") + + result = _run_validator(wiki_dir) + + assert result.returncode == 1 + assert "references a missing image: assets/flow-dark.png" in result.stderr + + +def test_rejects_non_png_files_in_assets(tmp_path: Path) -> None: + wiki_dir = tmp_path / "wiki" + _write_pages(wiki_dir) + _write_assets(wiki_dir, "flow.png") + (wiki_dir / "assets" / "flow.svg").write_text("\n", encoding="utf-8") + + result = _run_validator(wiki_dir) + + assert result.returncode == 1 + assert "permits PNG images only" in result.stderr diff --git a/uv.lock b/uv.lock index db3e3cd..d7e8fab 100644 --- a/uv.lock +++ b/uv.lock @@ -95,6 +95,86 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "contourpy" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/ba/01bde9753bdbba04a6da9d2bff3881f021bc708f654655e95fae26d3b3a3/contourpy-1.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:186ba929df36d61b6127da2e89cd1357e4cb79aca647381ab1a6feb0b152877b", size = 297302, upload-time = "2026-09-11T19:02:45.103Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f5/c5bf67522d49a2222f3154fe46879451d26f0e35ece41770758a64ea78cb/contourpy-1.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c76f3a5318164db7d9401132fc1b5364b784c613c93fa506e3b5e6d1bf353ec8", size = 284921, upload-time = "2026-09-11T19:02:48.049Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cc/cb989599eec12fda312e127eb8e04a8b21a7a6c94bf7ff1bc68273334a42/contourpy-1.4.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:43c3ccbb32c6294b183dcc8e8c46dacf5ecef809497e3d48a5be298eef185ad0", size = 356332, upload-time = "2026-09-11T19:02:51.408Z" }, + { url = "https://files.pythonhosted.org/packages/47/fb/6f620d7602507817b0b4c21dd790ed68688f1f4ae9c29aacf21f08db5cf1/contourpy-1.4.0-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:86d05cec773c9507a3950122e0e40ce77c23c75ceeb2fc189514e71893cbb34b", size = 405878, upload-time = "2026-09-11T19:02:54.093Z" }, + { url = "https://files.pythonhosted.org/packages/32/4e/693c6d6bdece679f0953775eef3a1b66d56be55478d936e7deb1f3004422/contourpy-1.4.0-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2deb580178ca19437a84bd77e4bc2cd91a8ccad212413a83c273900868b5978c", size = 408296, upload-time = "2026-09-11T19:02:56.528Z" }, + { url = "https://files.pythonhosted.org/packages/78/f9/b6831508960d559581c448532ba4df312217072975486dbf2b24fcc5b76f/contourpy-1.4.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591", size = 383243, upload-time = "2026-09-11T19:02:58.638Z" }, + { url = "https://files.pythonhosted.org/packages/f2/21/52903825a0ae7bb625e8bd30a09816d4c3c5d6174a469c10a616166cf780/contourpy-1.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f863c6100bf926cf47d13f3cd75f9bb8ebd98aaab230eeb4468b91f98f39a6b3", size = 1357306, upload-time = "2026-09-11T19:03:01.036Z" }, + { url = "https://files.pythonhosted.org/packages/d8/79/d68b1ce8539e4071518fed9523f558398f34dcd078b8927b109c72dad2ef/contourpy-1.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f", size = 1427243, upload-time = "2026-09-11T19:03:03.866Z" }, + { url = "https://files.pythonhosted.org/packages/ac/f0/b75a10e9d0616b97a30de277b6dfe83f1879880854c7330337309530eb48/contourpy-1.4.0-cp312-cp312-win32.whl", hash = "sha256:5450f091ac1be0be3ad3a2a3b3f23b5e443e78c670ced4fd347d626f92a28fd2", size = 347345, upload-time = "2026-09-11T19:03:06.192Z" }, + { url = "https://files.pythonhosted.org/packages/50/a9/dab08786bb4d77ef9a046b3c1be923be4e73c5d07d91f5a54e8ea9b09e41/contourpy-1.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c", size = 234083, upload-time = "2026-09-11T19:03:08.122Z" }, + { url = "https://files.pythonhosted.org/packages/47/b9/3ba509755a970dbde5948e7142ac21f266be72f38017cc4087a05fdceee1/contourpy-1.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:0c7a4c2716a4e98342221954416a836cca77c996c14ddbf22b5f01d5d93ca09c", size = 559521, upload-time = "2026-09-11T19:03:10.047Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8b/62a6eacea08ea0b6ab0159a7783df7ed421ff9c1ff58fef7c31f58fa5e52/contourpy-1.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e21d1d4a9db5b3a793649c7ab0ddb4697f2818929eec871a7b9c45fce7b2a1ea", size = 297330, upload-time = "2026-09-11T19:03:11.809Z" }, + { url = "https://files.pythonhosted.org/packages/3f/2f/103cdc5b7077cd569989d3ddb99ee3d4e96ee31bde8df2a6e426b2dc6195/contourpy-1.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:196759a3e4db60e1546167e361090ebb6d199aa3aafc9e34ea17a5ac3b23e814", size = 285037, upload-time = "2026-09-11T19:03:13.781Z" }, + { url = "https://files.pythonhosted.org/packages/bf/25/97001d1fdf940e6f5adfc592d4f5899fff95daf7dceead3988fe09987d2d/contourpy-1.4.0-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c0e07c691f3b3321913ed9b8161c50ea5f77fadd006f52f5e755359b0dcbfc5", size = 356675, upload-time = "2026-09-11T19:03:15.374Z" }, + { url = "https://files.pythonhosted.org/packages/a6/5e/9a7241a89e2f74402aefa2569e1349ad2750ff77823c04c788eaaedb7fdd/contourpy-1.4.0-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7f861af508fca2384eef392bc1d8377cfa349b2b854cb11b45d89c75780e2561", size = 406990, upload-time = "2026-09-11T19:03:17.44Z" }, + { url = "https://files.pythonhosted.org/packages/36/81/3a4fbbf6a806eada5453a6d16f6c7d96b9f4b3e57a3127368fb545986b8a/contourpy-1.4.0-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a03b32c2e7eda8b17757c022162c13c86f5c3d6f937dddf9ba3c3ff7b513953b", size = 407271, upload-time = "2026-09-11T19:03:19.523Z" }, + { url = "https://files.pythonhosted.org/packages/68/77/8f93ecbde1a4d11dfd460cd19a0c159f5487352e751fa87f5d78cc9db08e/contourpy-1.4.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f1219a8898523cba821085f2da8a1b962cc696325763f09d7f93538ba43b2d70", size = 384707, upload-time = "2026-09-11T19:03:21.208Z" }, + { url = "https://files.pythonhosted.org/packages/05/07/e5cdf94d68961ee464de6b4fedd3d2f666584f59ccd124bb1290597122ab/contourpy-1.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:20da2f86bfaed60dbba729fe738c8241b1dd22b6cf7e8cbbf30df290bd04ba28", size = 1356741, upload-time = "2026-09-11T19:03:23.621Z" }, + { url = "https://files.pythonhosted.org/packages/fd/8a/2301d07accb257ac08daeb631875fada06fedd019c20ff7b00ee07e9d211/contourpy-1.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6ced1670fafee703b8277ab1645072a226e74f167166eae146fb743916119b67", size = 1426793, upload-time = "2026-09-11T19:03:25.955Z" }, + { url = "https://files.pythonhosted.org/packages/7d/5d/a62648f06259d15c139b14eb8cf3c58fe53cb970a55f2bb77d1070e80a41/contourpy-1.4.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:abd0f7e51ecc52bf8c95713bd80b1c17c516a71fa391c54475308a4377903c2b", size = 117961, upload-time = "2026-09-11T19:03:27.713Z" }, + { url = "https://files.pythonhosted.org/packages/71/31/c5b7771ba6982f319ec90c0cf5c425b36891adfeee2d9f667f90b2d0c166/contourpy-1.4.0-cp313-cp313-win32.whl", hash = "sha256:510f7d93d94cf6ebf4e2cd0640bea16ab8affac7547230175b6745b596ce0599", size = 347438, upload-time = "2026-09-11T19:03:29.829Z" }, + { url = "https://files.pythonhosted.org/packages/68/c1/a59df0754bf83a6f3e153cc19d550a5b01f607e389b1c4d57f436f9139e0/contourpy-1.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:6507a016976a75a15aee47809a34605de6244ccc056e6164bf9fb14b27eecad4", size = 234084, upload-time = "2026-09-11T19:03:31.657Z" }, + { url = "https://files.pythonhosted.org/packages/41/48/97224f5decb1efa5a610f912195deb45321f73ec9b9dac485cd6fe2d5a6a/contourpy-1.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:423bd5f4b3f11d54a8c597234e513382e3454bb106b8ec7ae32ba4ed63f8d99b", size = 559559, upload-time = "2026-09-11T19:03:33.528Z" }, + { url = "https://files.pythonhosted.org/packages/75/b0/b548628c8dddf6e5e0a981b7fa8e4c008024df09c7d17c6a9e271edfa0b3/contourpy-1.4.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a3e67bc1a6a4618a1dac7c3053a9ffece5ddfa2046b2670b342cf430bb0b87d1", size = 297354, upload-time = "2026-09-11T19:03:35.017Z" }, + { url = "https://files.pythonhosted.org/packages/04/5a/513484208742f65af2648c519f0b7ab034616e183c4403538024c136a1ab/contourpy-1.4.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:072a702e2e178f4fcf96f04775d0c059e4c917925abf0d3208ebb6865df3c23d", size = 283729, upload-time = "2026-09-11T19:03:36.818Z" }, + { url = "https://files.pythonhosted.org/packages/35/da/5a6562febc994b2c4bf9d01e57a50458ef8a2051bb3e7b35a00333e0fc26/contourpy-1.4.0-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:404dbcd9233513dfd1323b66ea593fef90e899f658f6b8a9ed8e93bd0ca669db", size = 357819, upload-time = "2026-09-11T19:03:39.058Z" }, + { url = "https://files.pythonhosted.org/packages/6d/99/7b358ce888aaa426f755daa096c99c59d17c352037344e836f20e5d3b957/contourpy-1.4.0-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:61624f6722480aa7e168fd746164e7bfdf48f8ccb6542f1613741200dc37e2b1", size = 407795, upload-time = "2026-09-11T19:03:41.293Z" }, + { url = "https://files.pythonhosted.org/packages/be/02/34d7548adf08c60967435d79d7a90882eacc84f5093435287974c7e99943/contourpy-1.4.0-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e741a39dfc96babe1722561e81351aeec104526c57dbe91c167c1db606c2d55", size = 408552, upload-time = "2026-09-11T19:03:42.728Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8c/9677dad226e5aaac5b823d5b09d881ebc32ff1648af417597649841e516c/contourpy-1.4.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e439ab450c93455feb0218532ded3e946ec7a9b5f459069f122cfa44b89229f6", size = 384850, upload-time = "2026-09-11T19:03:44.402Z" }, + { url = "https://files.pythonhosted.org/packages/08/f5/e3fbeaa489c223629fbb434737cb3de4ecaca9cae4825e77b92490f640f8/contourpy-1.4.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:417be048f7e122cefbe2a34c51a1f2b0410f8eb35796f794d45475ddb7872d9d", size = 1357601, upload-time = "2026-09-11T19:03:46.746Z" }, + { url = "https://files.pythonhosted.org/packages/88/be/55fec293d342c222ed58a5d4056df4362e192af2e59527a3d5d822de8828/contourpy-1.4.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:43d80072a32299bf945de0a6dd4e034ea0162e832261de2e07a274a5adbba9c9", size = 1427340, upload-time = "2026-09-11T19:03:48.745Z" }, + { url = "https://files.pythonhosted.org/packages/86/40/0faabf453edf59b0e3633381d7ca72c3414fb9b72b5cbb08b06ed792d3e5/contourpy-1.4.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:fa1b787362a3856e63dd2b89449f6c384d55ee1beb8f94f4bcc871b40f02462c", size = 118355, upload-time = "2026-09-11T19:03:50.047Z" }, + { url = "https://files.pythonhosted.org/packages/38/0c/7ea75aa3559ae8a6805015e15a19c92b6480752ecc92526361e5776e88c5/contourpy-1.4.0-cp314-cp314-win32.whl", hash = "sha256:738c44fa71735a617f36da58e32810512407d283d5d1bb5b1cecb00d7eeba7cf", size = 356977, upload-time = "2026-09-11T19:04:11.401Z" }, + { url = "https://files.pythonhosted.org/packages/15/41/3df8cc14bb572c8b447f9dfbc876703f0f2f2896058285b5c87a1d4a638d/contourpy-1.4.0-cp314-cp314-win_amd64.whl", hash = "sha256:181bea01bc742734ae672fa00c717d855dd35e1f029536406538c52e7b0cd73d", size = 240101, upload-time = "2026-09-11T19:04:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/66/01/ee6830a5aa4565662a345172f6f35eeeed625d20f1c9d4ecd35318fe4ade/contourpy-1.4.0-cp314-cp314-win_arm64.whl", hash = "sha256:64039341e2d8804f1a13bda8c69083eab935167bbd7e856cf096241f17d5bd45", size = 576359, upload-time = "2026-09-11T19:04:14.983Z" }, + { url = "https://files.pythonhosted.org/packages/51/af/49ee9c9cf012699e505c1b63c531cc99f19df50f205173092c4d541e3ec7/contourpy-1.4.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ef47fef9a912c77e3d84b014f701e5a9340f25703e9ed3bcebe37f91fb69dc49", size = 313601, upload-time = "2026-09-11T19:03:51.452Z" }, + { url = "https://files.pythonhosted.org/packages/ad/59/ce411ab2be0f805038626d8f4ca9ce563487ff51ff6c363e7512271564ed/contourpy-1.4.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:96019f059bcb3774acc0104be3360a57b36d33eaaa2e1d7f77c800ca8e07618b", size = 302812, upload-time = "2026-09-11T19:03:53.022Z" }, + { url = "https://files.pythonhosted.org/packages/95/b0/390915f9af14c1e2d3b2a9ad99d85b98df4352346a51e368cbb825f813c3/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ddf5a2596d716fd3793434844caf31abc7a40b1e8718431420c89858268fb909", size = 348996, upload-time = "2026-09-11T19:03:54.594Z" }, + { url = "https://files.pythonhosted.org/packages/c7/85/e0952576d54322f3e9983b1e049a7a31f42ce82c5c29d01821e6dd3780d7/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:dd59df9e2fb0aff8bd7fd1adb9f349b7c835245a9d0f18c2f2deeb537190f2b1", size = 400272, upload-time = "2026-09-11T19:03:56.822Z" }, + { url = "https://files.pythonhosted.org/packages/d6/7d/f13543a5e1598e4a4ad01d9d5e2d65f9c09c37660616429913d606c5977d/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b7794ea07cab575633daad8d6e963b662053391022294d3aacc1d9ba9ef54114", size = 412895, upload-time = "2026-09-11T19:03:58.487Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a8/6e5eaff53507dfd2dfc428240eecda32453067277d4b3e7ca71210b2d611/contourpy-1.4.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1c8a74744fa746eeaa12f0f9ed7f8b4add9d8f1b14d95e3b5e133675eac888f", size = 377060, upload-time = "2026-09-11T19:04:00.122Z" }, + { url = "https://files.pythonhosted.org/packages/16/a3/d00e44d35511b3cead5bd794ee672d4eecf30d9de4ceac57a49d6204064f/contourpy-1.4.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:107ec46f7aa1664266d69b1181aadc953d58d39f7d8d648fa5b795d4a060b0de", size = 1345688, upload-time = "2026-09-11T19:04:02.705Z" }, + { url = "https://files.pythonhosted.org/packages/1e/01/1e533b0cae32c8edd63fe40435ec3b29345dab87321afcd28722d7f957d1/contourpy-1.4.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5a4c89c7f38a0d7a94356d74e3391073c4325c4d47ad2fd065c3fe7dbae16c0c", size = 1416140, upload-time = "2026-09-11T19:04:04.77Z" }, + { url = "https://files.pythonhosted.org/packages/6d/0c/4ee66759f00d6a5d6909782f14f441d639fa18a4a43142e334351efc47f8/contourpy-1.4.0-cp314-cp314t-win32.whl", hash = "sha256:912c6afaa106e2f74ba22b30416b77ef7eb94e3bdc5a4df51ab147845dba9b6d", size = 371982, upload-time = "2026-09-11T19:04:06.233Z" }, + { url = "https://files.pythonhosted.org/packages/e6/ac/b3e5324138c3e3741f526663f4f265f4f69dfdf26415a39428940864a5f6/contourpy-1.4.0-cp314-cp314t-win_amd64.whl", hash = "sha256:ef9440f6f8506246269a82734f5ff9e2e4c5e775b3996fc883cc491c5257eca6", size = 262907, upload-time = "2026-09-11T19:04:07.882Z" }, + { url = "https://files.pythonhosted.org/packages/19/37/c9aa45e47819dc15a38fc5c81a2fb987fde55e9d3b991fbde514e3b6b5f5/contourpy-1.4.0-cp314-cp314t-win_arm64.whl", hash = "sha256:fc9feef8f1f001c5b87decadc67c4a5d1eebb62ca39c4763d1237ff62cf2b707", size = 587071, upload-time = "2026-09-11T19:04:09.898Z" }, + { url = "https://files.pythonhosted.org/packages/cc/74/66d4e6fbea3bcb3fd4e5ae21c039ba31b8fc408b35884b4bc09b88016dce/contourpy-1.4.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:79b06c60d5e569ce12c5da8f0c51217cdc484386e2349fa717c30fafb56d2871", size = 297358, upload-time = "2026-09-11T19:04:16.718Z" }, + { url = "https://files.pythonhosted.org/packages/2e/8d/8f7f25e71d73f15d7859943189900d2d348e740388c9ef52a0180d284762/contourpy-1.4.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6f963ea9f0d68d2b6a02d861e3c0aae09ae25ba21f243fcf281e9fed468b078d", size = 283732, upload-time = "2026-09-11T19:04:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/f0/90/957549e3b03c407c670e3e191db63f4aef60dab6605bc967af3a806b543e/contourpy-1.4.0-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5545ff38229c15d11d822fc6f7415b932da9f4975f53e305b7b96ebfb01f889c", size = 357820, upload-time = "2026-09-11T19:04:20.077Z" }, + { url = "https://files.pythonhosted.org/packages/56/4c/fa8de87d907b41b05d03f4945a51675cd67319650d01b4c927d209ffa6ee/contourpy-1.4.0-cp315-cp315-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:630d32f06cedf37b7f1dd2b6a12e4492826bd477a4c9c7b2e2fee6ce3a2cea76", size = 407804, upload-time = "2026-09-11T19:04:21.781Z" }, + { url = "https://files.pythonhosted.org/packages/04/e7/96bd4f4a4ae285727befbdb4b332d53a2654cc5da4585d2525b47a063e1f/contourpy-1.4.0-cp315-cp315-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:be85d160e7c795113c2a93254dde2fc7e86b375322570eee78b420969426973c", size = 408559, upload-time = "2026-09-11T19:04:23.432Z" }, + { url = "https://files.pythonhosted.org/packages/ae/94/39660e8dc309f96bf7971eb4ec5659f272f84e42b34c9990a96ecce8442c/contourpy-1.4.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:018227e134b73090b06f911e773a526c77c9af426be29065500ce096a5accd4c", size = 384861, upload-time = "2026-09-11T19:04:25.198Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7b/411dccbf73d5d19da49bf7735786b3baf4ddb1456412d48ae4d4ab1fc761/contourpy-1.4.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:4bffcb2e8cc5c0e837631acab59dd04265fdac376550e7c3e310523877c68cb7", size = 1357612, upload-time = "2026-09-11T19:04:27.614Z" }, + { url = "https://files.pythonhosted.org/packages/a0/39/bf2442130e7d5aae75a4de4504f0c8aca3ef3da3feac3940ee27ca985d83/contourpy-1.4.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc87f2ffa84a49a77d76cb792f28a48ff3b05a222aa0b2bddbd839ba78e1d5ca", size = 1427345, upload-time = "2026-09-11T19:04:29.646Z" }, + { url = "https://files.pythonhosted.org/packages/96/60/e5d9196dd83ccd7dd103762982b10ef19a4f72e8ef67ae7157699b9be0bb/contourpy-1.4.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:c8be3392b84cf43373a488874dc1ebf46f60784a70977f92586e18019d71c7ed", size = 118157, upload-time = "2026-09-11T19:04:31.091Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b2/ae3d90f08ba2ed82189d93b55ffbd41e559760e89af4f9ef54d51869f41d/contourpy-1.4.0-cp315-cp315-win32.whl", hash = "sha256:618137ec5778fb76d494c9ec854b104a377fddba0d128bef7136cce2c3bf0df8", size = 356982, upload-time = "2026-09-11T19:04:52.913Z" }, + { url = "https://files.pythonhosted.org/packages/02/a0/36648fff407dcf8b8482985d33367ffc0fe90be72383869312cd0bd00a1b/contourpy-1.4.0-cp315-cp315-win_amd64.whl", hash = "sha256:ea09dc704029930cbd097f75cb0cc1db9852adbcf1a151fac7e9559f7bcbfd19", size = 240101, upload-time = "2026-09-11T19:04:54.587Z" }, + { url = "https://files.pythonhosted.org/packages/07/09/49e987a96706b8f877596cee00d558d7880793a833addc6b33f80805e5dc/contourpy-1.4.0-cp315-cp315-win_arm64.whl", hash = "sha256:a5e2bb871b90cd7a52bdee63bf80ef7acb46398d27efc66d7679240016efc5aa", size = 576375, upload-time = "2026-09-11T19:04:56.515Z" }, + { url = "https://files.pythonhosted.org/packages/e3/18/820ba24a070fe2a834af73e52245c501960746f5c1777ebc64ec0c0dec12/contourpy-1.4.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:432e89f835cf01f8d2123a130a3126b17ee6e0348e4d62c0973872b30aa873bf", size = 313543, upload-time = "2026-09-11T19:04:32.582Z" }, + { url = "https://files.pythonhosted.org/packages/d3/4c/f61a63d8107e0c1c3fa47d30ce45abad90b2ad48a1a9a4510332db7e0176/contourpy-1.4.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:3e0a2392533e5e2abdf277c951047516acc8d2f3c42b2dd9dc34c907c9ebabf2", size = 302702, upload-time = "2026-09-11T19:04:34.257Z" }, + { url = "https://files.pythonhosted.org/packages/9d/93/5af95cb5113ecc6e780ca0c6c79756a2cea8833f971bbae112dd4ad73ded/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:758e7496cec3195fc28a28945eab3ceef348c47fb95c7afc2eca2f3901209c8c", size = 354370, upload-time = "2026-09-11T19:04:36.158Z" }, + { url = "https://files.pythonhosted.org/packages/47/75/5a9942446647202beb7b4d150891bfcb78fb112c73862484bbe4cc031092/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bee6ff96653e0807cd0f8eaef00174a031e3a2effa5c20f49a5a8d574b05af23", size = 402340, upload-time = "2026-09-11T19:04:37.914Z" }, + { url = "https://files.pythonhosted.org/packages/c3/4f/bfdb0c67775a584f957211936661289789c4d0ec3e988bca2c8c02f8090e/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a58b5f130afec61a093d743cdda435cc4047748b6791627e34a68f41ec3a9b07", size = 410721, upload-time = "2026-09-11T19:04:39.925Z" }, + { url = "https://files.pythonhosted.org/packages/65/d3/dddf13d6bb26e145c99debd1f2695018b5f3e24452dd9bfc9904c9d2ec89/contourpy-1.4.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b9dc493e7924e5aa32d89d0b8e50986280f3d4b284968a792787bd7bcffd3cad", size = 382604, upload-time = "2026-09-11T19:04:41.793Z" }, + { url = "https://files.pythonhosted.org/packages/37/b4/89f0a5f6c6ccd322eae2704c7e933c82a4e594a61773933b4b0a18646866/contourpy-1.4.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:c927ec747633e68c9920bcaad48b0bcefe648812b822f18c34e2d0e2270a3d2a", size = 1354996, upload-time = "2026-09-11T19:04:43.856Z" }, + { url = "https://files.pythonhosted.org/packages/5d/29/fc91cc1ac6f3b591a269f4357b656d6ed0c39eb17c148f41f6da2f9729b9/contourpy-1.4.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:80c7fc8e7ac217777ce7ba2db3cf8478652b5a4b335283111012ff9eaac9d842", size = 1425030, upload-time = "2026-09-11T19:04:45.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b8/bb129f524210c5d3eb8616876e02af280fba8b5554e0ac1afad80b51e06b/contourpy-1.4.0-cp315-cp315t-win32.whl", hash = "sha256:90feb8da006803a95ba573fddc9536357d0c3faddc3a4c9e22816ca49af52878", size = 371854, upload-time = "2026-09-11T19:04:48.106Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b1/bc774d9d200cfc4f073bba78b1bb1cb3b55bf1c8c345eae41fc2db510459/contourpy-1.4.0-cp315-cp315t-win_amd64.whl", hash = "sha256:de503609fdb71f597634ca64fb4bd2f13d27c97f140e912b1e8ed93544840df0", size = 262450, upload-time = "2026-09-11T19:04:49.502Z" }, + { url = "https://files.pythonhosted.org/packages/54/bf/eb4ff492e1c3d027617b5a20e4e6d63a035b41b8cf77a95950159556a3a5/contourpy-1.4.0-cp315-cp315t-win_arm64.whl", hash = "sha256:78ed5c5f962b3e156109f0531b174a65ba80d13cc681a70227b12524c162e184", size = 587064, upload-time = "2026-09-11T19:04:51.148Z" }, +] + [[package]] name = "coverage" version = "7.15.4" @@ -194,9 +274,81 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b4/d9/e70c286c979378f061d8266e279b686ab0b0b688e1fe0af864684f23a77d/coverage-7.15.4-py3-none-any.whl", hash = "sha256:964730a1e9de9c0cf11be6a1a3c79ce419c34882842abd256086ba4698705e84", size = 214332, upload-time = "2026-08-06T13:50:22.192Z" }, ] +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "fonttools" +version = "4.68.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/63/f332b2099599b4911786a6f6fd69552fdd5ae6a45cfaffb0c881092f36c8/fonttools-4.68.0-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:f265c85432c398d86f26add143423924a4747879b2dce001a3ffe0a5fed30638", size = 3143556, upload-time = "2026-10-27T16:28:21.812Z" }, + { url = "https://files.pythonhosted.org/packages/c8/97/68816bb56843e06631ff11517e4fb35fc62d76aec6e29f11df095e7f33c5/fonttools-4.68.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:d225096687fc3bac0ebe3357e95b2dd8b0a49d191f016db0771d537ccdd6f47e", size = 2633689, upload-time = "2026-10-27T16:28:23.54Z" }, + { url = "https://files.pythonhosted.org/packages/21/94/b125c7a6d154d17f4f699150ef3abebd9d8ad0f7eddce9dad649a9e5c1d8/fonttools-4.68.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b41e71b2657c9843b2327b4e3c116db1757dc8cd05d978cd47cb5061272d4997", size = 5462605, upload-time = "2026-10-27T16:28:25.774Z" }, + { url = "https://files.pythonhosted.org/packages/7f/58/fe13db71e3f5a020c6875f349806e84f7550f3f24cb3cdbabdd693968b1d/fonttools-4.68.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3edce69ecdefa73ab1041901ca22eefed6ebb93a77bc77e889d940479f25bf7d", size = 5443448, upload-time = "2026-10-27T16:28:27.898Z" }, + { url = "https://files.pythonhosted.org/packages/f1/7f/48236f8c626007670586dd6b0d61ed80323a6b17ead763c881d717525cea/fonttools-4.68.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:d8d5674de2b614575f0751671727056af042ac1d61beacb59a298d74282fa492", size = 5399992, upload-time = "2026-10-27T16:28:29.99Z" }, + { url = "https://files.pythonhosted.org/packages/cb/0d/09e9a433430e277e454eace1c4d02c3691a33d5257bd234702a427a9d090/fonttools-4.68.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:7ab8097e7e191784974c5608eb95fb31e1243fe3054cb66778ac82558e9b36f8", size = 5563739, upload-time = "2026-10-27T16:28:32.691Z" }, + { url = "https://files.pythonhosted.org/packages/ac/54/6708f4c6742de2d5bf4280d8bde22fb8aef5120328bdc19ca34a9d2e8e8b/fonttools-4.68.0-cp312-cp312-win32.whl", hash = "sha256:1695cd2e1f9768fe3f14d369ce6ef1b3e8561069cc9e47059571985d1ea42614", size = 2481614, upload-time = "2026-10-27T16:28:35.122Z" }, + { url = "https://files.pythonhosted.org/packages/1c/3e/ef786310a3774ae7aacaa288ca6d1e1dfd03c24214137478e4b630b76af0/fonttools-4.68.0-cp312-cp312-win_amd64.whl", hash = "sha256:fedc183bdbc3fdbfbdca26e0e04566d089cbb404712509a4e824608e9304cc77", size = 2533508, upload-time = "2026-10-27T16:28:37.085Z" }, + { url = "https://files.pythonhosted.org/packages/06/11/2cc4272ddd485c448c0363be9beb0a24d3f429f1cc8c5aafa716c508e899/fonttools-4.68.0-cp312-cp312-win_arm64.whl", hash = "sha256:95628bbc5ea81d5761268f4c4f1ba709af510b970f363498ac801c0c1fd7a4a8", size = 2502049, upload-time = "2026-10-27T16:28:39.355Z" }, + { url = "https://files.pythonhosted.org/packages/05/ae/e2d75b7f582c1cc018ab94b8bbfbad7ab501b340debfa256f48125cae3eb/fonttools-4.68.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f15de48b82a816c72f358e772792801bd3788a156caa76e1806cb0aa8148cd61", size = 3141370, upload-time = "2026-10-27T16:28:41.721Z" }, + { url = "https://files.pythonhosted.org/packages/fe/80/73d5297441b42d42b64d91cd4fffdff1541fac6171b0aca0a167c26d1c33/fonttools-4.68.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:86d319a1feedfc75c8ff582d947b21fa1854e2829cb8cf9428784d750a05f1d9", size = 2633412, upload-time = "2026-10-27T16:28:43.612Z" }, + { url = "https://files.pythonhosted.org/packages/36/29/16501aa69a586b8e8f810d7be19584aa026a0bca46c598ac516cfdd2a31a/fonttools-4.68.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:04a4868dcfcc23f00bb033147d5afc1a118a992842644c3eb9da55467ab4fd74", size = 5435968, upload-time = "2026-10-27T16:28:45.651Z" }, + { url = "https://files.pythonhosted.org/packages/79/c6/4b44abbffa01f85d6d0f0b9325a712019b4e2e6208f999ac6846d8da1346/fonttools-4.68.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08851f7d2b983412f490b73a7c56f17cbda1d4d85d2ad3f857564bf15b5d9475", size = 5418193, upload-time = "2026-10-27T16:28:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/98/0d/15cffdf13e156bb75ee421eee319fa8c5fb91a48a9a3e84685bf786df5be/fonttools-4.68.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b6f7c5fabf5b1d9ca79f204664f2c3e2f8218e50aebc43e85e02df0b2d9cc313", size = 5378957, upload-time = "2026-10-27T16:28:51.889Z" }, + { url = "https://files.pythonhosted.org/packages/9f/18/174052f12611c1088b61eeaa4019a8f1aedbcb1e985c33ef8fbe0c1ba674/fonttools-4.68.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3ecdb0b248cd0bf43100a8b3cb40f7b45d52ea4be8616edea5dea8fefe90229", size = 5536796, upload-time = "2026-10-27T16:28:54.445Z" }, + { url = "https://files.pythonhosted.org/packages/35/d6/892213f45f63565f3f7eca3bce484a6f52ab7f7eda61851f93b1be829d5e/fonttools-4.68.0-cp313-cp313-win32.whl", hash = "sha256:4da99b83ae17f531838bc750abf56164ff37e1543e8e9b2b5403548f50497ce0", size = 2479972, upload-time = "2026-10-27T16:28:56.749Z" }, + { url = "https://files.pythonhosted.org/packages/61/2b/6c6f578176edeec83c5e02b7e745c1c8029f8cec4e32b4898d2c573bb881/fonttools-4.68.0-cp313-cp313-win_amd64.whl", hash = "sha256:6ed796b220654b4d37ad20af73419ec7969b669dd678cab88afb602c5683a331", size = 2531658, upload-time = "2026-10-27T16:28:59.013Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b9/7cc71534bc954346451003bf5c9c117af835aea681a13a2847222ccf19b2/fonttools-4.68.0-cp313-cp313-win_arm64.whl", hash = "sha256:cd4b0d00523cae1e5e1eaed1d2b85ef342cec000f58d0738e12b064d72a7bbc2", size = 2499695, upload-time = "2026-10-27T16:29:01.511Z" }, + { url = "https://files.pythonhosted.org/packages/1a/70/ee6655887166a111d0c4d7ca61f03c90b141cdc6f70c85138fd0b8bfa2e3/fonttools-4.68.0-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:b2ee7b9c1a5e1d637073c39b0978956febad7e862a1269719f527934c65535a4", size = 3145377, upload-time = "2026-10-27T16:29:03.757Z" }, + { url = "https://files.pythonhosted.org/packages/d6/37/66e7ab417660cb2c65889eb5ad8d80cc5a7cb2c09dd1becdbe6d56bac4fe/fonttools-4.68.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9d80813ae74b969ef2166a3040b591826e80ecd879bdeab7f13f4e8eaf08b345", size = 2634889, upload-time = "2026-10-27T16:29:05.651Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ad/da985167af1988b82112cf133e826cf075cecb28d120778589265cb3125d/fonttools-4.68.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a6837def5de49772b82683dadd836df214def04b307cb98d0e7723d49e7e15bb", size = 5420416, upload-time = "2026-10-27T16:29:07.502Z" }, + { url = "https://files.pythonhosted.org/packages/b7/67/e9f2eb2aed41d4ed251a3c6f66e104685f0a03d8ded7ed87f1f0fc63898c/fonttools-4.68.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cbb63b26d33acc3eb61f544c22a0cadbe01682fc064b266bb0e33fa66cea853f", size = 5363969, upload-time = "2026-10-27T16:29:10.172Z" }, + { url = "https://files.pythonhosted.org/packages/e6/06/c4510ac6b43b374b1b707b99fdd0ba1d4059d2fb516584a412c0396fedef/fonttools-4.68.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:81ea963d4390bb9e79f91a905310d91ac7ff7675d8e1c0cfc0f1712521c41a43", size = 5362373, upload-time = "2026-10-27T16:29:12.298Z" }, + { url = "https://files.pythonhosted.org/packages/e0/ef/ea0bf283a30a88a84a47078ff39f7bdefa0346a8bd7737439fd33084031f/fonttools-4.68.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:3b9b87645bcdbfc3f30240e2758a37bbef4fdd0f708683b2bfceb60975d63e59", size = 5495553, upload-time = "2026-10-27T16:29:14.614Z" }, + { url = "https://files.pythonhosted.org/packages/95/c0/d493f8c8974859e57920ce193ffbe277423da7eebccbb9241bc31e1b5f1d/fonttools-4.68.0-cp314-cp314-win32.whl", hash = "sha256:39913c1f576af86c69519dc351302332561ee62b39fed04dcfa8019d9c2d129f", size = 2484057, upload-time = "2026-10-27T16:29:16.45Z" }, + { url = "https://files.pythonhosted.org/packages/96/41/c9ca629ffe1b883c1422540a8a11a4ea09616366ab585ab4ee9833f2cd75/fonttools-4.68.0-cp314-cp314-win_amd64.whl", hash = "sha256:1782f2cf952eb262c4126b1f57b5f0e027e71bf2b632350a033dec526f448428", size = 2536130, upload-time = "2026-10-27T16:29:18.399Z" }, + { url = "https://files.pythonhosted.org/packages/17/40/f6264c988076393db3e0b00d6d0ea2a53ce40d445e8a196be241d16d362c/fonttools-4.68.0-cp314-cp314-win_arm64.whl", hash = "sha256:f0b39924698a85bee107184a3c2ee9ae27248144977160534f7d558831db50cf", size = 2508386, upload-time = "2026-10-27T16:29:20.318Z" }, + { url = "https://files.pythonhosted.org/packages/c5/d8/a4d710362f3f23aecc16015eeed1d602187189af7f63a63546233ad2fa73/fonttools-4.68.0-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:956230858b7a7bb9f5e0971ae07dc64b6155307304acd8c62aedca30e6aae874", size = 3219047, upload-time = "2026-10-27T16:29:22.337Z" }, + { url = "https://files.pythonhosted.org/packages/4d/4d/0d516a1d3d34e84c56237ba1d8dfed8575c350b0e8d39aa30b518d089daf/fonttools-4.68.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:b637d82a488116da2869afbddccfd93ca14e3c47b404c8ec5a9bad9d4381b08c", size = 2668060, upload-time = "2026-10-27T16:29:24.536Z" }, + { url = "https://files.pythonhosted.org/packages/4d/40/56893c685cb1ee7d7ee30d0ac94adf92020787cf5a8e15c2e4e6944f0bec/fonttools-4.68.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:419bf78474adaa6fb320a06822f4f941b19345d598a9de379d6e2f0e4d819df6", size = 5593080, upload-time = "2026-10-27T16:29:26.51Z" }, + { url = "https://files.pythonhosted.org/packages/41/b6/bc0bbad6f1aef22519c4e731c6dc8655e92c6f7204277ec36502ea7e76cd/fonttools-4.68.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:fe80d05dd85e6ac58d0cd4fa10ddb96252a6f1046ee0fd00cd1d48f0c25921ac", size = 5399669, upload-time = "2026-10-27T16:29:28.969Z" }, + { url = "https://files.pythonhosted.org/packages/c1/b4/4404a91dc699dd430732d366996cef6d8c8f61c758b5e544a76903db580a/fonttools-4.68.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:cea1969b9bfe230cb3fd66f1c66da5a63a9a917d9cd25a0839524d3d1a88b40e", size = 5460446, upload-time = "2026-10-27T16:29:31.15Z" }, + { url = "https://files.pythonhosted.org/packages/56/09/66876a0d1a01f7c16eb9f7c8ebcf064ebbd6b249f837691cb5a35780316a/fonttools-4.68.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:fde43b9785c7f105aa563b6b5481edabea4ab6be7d9ef14ff4d76225950923e8", size = 5495792, upload-time = "2026-10-27T16:29:33.455Z" }, + { url = "https://files.pythonhosted.org/packages/15/7d/1d702dc628e6f5b0d63be906025afc5e5b487cee48128943bb0a71d2bcb3/fonttools-4.68.0-cp314-cp314t-win32.whl", hash = "sha256:a325e6d7f96f20b3004658c5ed17ccfce5b66277b43ccd883035c61be6945275", size = 2517805, upload-time = "2026-10-27T16:29:36.929Z" }, + { url = "https://files.pythonhosted.org/packages/f3/42/8fa0741e08ae16be66a0d2e6d67f918fa0f2961bad70ccef84f9af0767cc/fonttools-4.68.0-cp314-cp314t-win_amd64.whl", hash = "sha256:e80ac66627a01698675ce6e98d90ea9817d1e06644129ec8b0093f66ff1cbeac", size = 2567666, upload-time = "2026-10-27T16:29:40.081Z" }, + { url = "https://files.pythonhosted.org/packages/13/2f/b73cf496570e8d2c66a6099f825505283ef8e944bd588e0b63036d6b2412/fonttools-4.68.0-cp314-cp314t-win_arm64.whl", hash = "sha256:83bd3d558c15f4e1d87b8f3fcfb337c2bce63c7e5c05212abc8fdcf15e216c54", size = 2532338, upload-time = "2026-10-27T16:29:42.073Z" }, + { url = "https://files.pythonhosted.org/packages/24/af/dda3fbb1da1d3cf5bf8cd6a924ab799fd2a483382df7de6f9770b543ef4f/fonttools-4.68.0-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:ab6505dfbe3199453d8542b25f55c1ea3260d38029d9db58c0c7304d438abdc0", size = 3139761, upload-time = "2026-10-27T16:29:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/4f/47/4294eececd4e7c38bcb98c78be96003b4bbfc459c30adec13104b83112c1/fonttools-4.68.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:03c9ef1272e464747f67c623f76449b888da6d5de7fb46275bb36488b9ceedba", size = 2633458, upload-time = "2026-10-27T16:29:46.202Z" }, + { url = "https://files.pythonhosted.org/packages/df/3d/3ee0940101d12a68cfd5e3d91380933878d99bd082eb9df348eb768b0375/fonttools-4.68.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5083a456d68d2995ab78600ccb18ec08c42f9bc14f0ef80c12e2e5b11cc371ce", size = 5417615, upload-time = "2026-10-27T16:29:48.404Z" }, + { url = "https://files.pythonhosted.org/packages/a1/ff/a97925464230d9c39c94e4cd7c5690db950373b34317e7f0ffe7b64b8d49/fonttools-4.68.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b65c2f3c4449383429507a7e1b372bd759f60a2df8ddc8d6c1cf9010585576b1", size = 5380964, upload-time = "2026-10-27T16:29:50.809Z" }, + { url = "https://files.pythonhosted.org/packages/ee/51/f467501a75bb383f1acbcc7a7d8ce196c02bea770e2bdc62d269c18a31a1/fonttools-4.68.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:039142b75a068c93f8596ef68787f82c74940b9153d24c224ab31e750eb083a2", size = 5357813, upload-time = "2026-10-27T16:29:52.892Z" }, + { url = "https://files.pythonhosted.org/packages/ba/1b/ebb9c32a19a89e8c5cfc63833d7edb70019d3184281452cbc1a24cadce57/fonttools-4.68.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:1dde2f0ec3fd0fb43cf818593b38a8202eb7f3b59cae86289a8b19fbf6f6313b", size = 5505577, upload-time = "2026-10-27T16:29:54.95Z" }, + { url = "https://files.pythonhosted.org/packages/18/c3/080bf6342ed37c4304cf222cf80afd2a145cd8f37a758d812cda81ba3e12/fonttools-4.68.0-cp315-cp315-win32.whl", hash = "sha256:4bc352572abc800177fba513995c01b1cfbe8c810ac2506cbf29f0795ae061c5", size = 2482863, upload-time = "2026-10-27T16:29:57.029Z" }, + { url = "https://files.pythonhosted.org/packages/f2/b7/8ce34a43072ac7b1a937c5a0ee8e024db5d774bdf07708bb7593f3e5540d/fonttools-4.68.0-cp315-cp315-win_amd64.whl", hash = "sha256:9b6e4ae9763c67df2b0f4c4f1a0b18e47ee6572eb602b82e798acc88b64a6137", size = 2535110, upload-time = "2026-10-27T16:29:58.999Z" }, + { url = "https://files.pythonhosted.org/packages/6d/35/d58d4ac6dd3de099c11c42486fc4a51b1ccb2c1c3259b19956e9244d5623/fonttools-4.68.0-cp315-cp315-win_arm64.whl", hash = "sha256:e00bfc6fc0158f156d34f923829e6f62ca00df2e0ea42ba3b0db4089b6d921c2", size = 2507240, upload-time = "2026-10-27T16:30:01.439Z" }, + { url = "https://files.pythonhosted.org/packages/29/16/034e1eee6264cd14ef4404f70c299a9b0570d83aca24a65ddf3a16ab3b42/fonttools-4.68.0-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:0841a4dac69efda309fca2ed0834186ee66d39787f1d26430ed7f779a699a096", size = 3210579, upload-time = "2026-10-27T16:30:03.601Z" }, + { url = "https://files.pythonhosted.org/packages/17/37/626504f427aa92d1d872336eab454ad71b6bc079063cc1f4af314995a48e/fonttools-4.68.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:93afd51f30ae38f7d826f4632eb799a06bd94e1fb4bc59fdce6d291e93491027", size = 2664302, upload-time = "2026-10-27T16:30:05.639Z" }, + { url = "https://files.pythonhosted.org/packages/62/13/bc455cb7f8e467ed4ea1146c1ecad76d6c78102031d937cae71efc176c42/fonttools-4.68.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:82b8024fbdcddc399b1e21575b9b82f46b8391e711a44d6bd4a1616b0aca3681", size = 5570974, upload-time = "2026-10-27T16:30:07.457Z" }, + { url = "https://files.pythonhosted.org/packages/23/06/33ce5c7d3bb59dda92fbf669053d5fdaac2e0d566390fdf20746ee83f39f/fonttools-4.68.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9fee5880486c3fd6f45f5a1679a9f4291ae74e503d725de7f1e30efa2d627440", size = 5392631, upload-time = "2026-10-27T16:30:09.587Z" }, + { url = "https://files.pythonhosted.org/packages/3c/c0/414f221a7da04ddb6d30a8171ecdba36e2ab4351c5c62ec319621ee76494/fonttools-4.68.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:4be32afa53ba3dea243b95b62e9b2e6ed6cf7096acd741d379c12f4113694ddc", size = 5438942, upload-time = "2026-10-27T16:30:11.966Z" }, + { url = "https://files.pythonhosted.org/packages/98/71/797da0cb0fdb3839b4aa65d30854b850832c74dc14ce0ba5bfe812c6a008/fonttools-4.68.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:6e73d4b1526343b45bbafa9badc0396a49d902f9a1774666ed4244f1df717629", size = 5485323, upload-time = "2026-10-27T16:30:15.074Z" }, + { url = "https://files.pythonhosted.org/packages/c1/47/a6989b4de0f427817f2e436f69664acc3aa9600d3df5f0eb3444cd073f14/fonttools-4.68.0-cp315-cp315t-win32.whl", hash = "sha256:573ccce8b5fd9b6952dcbc5d896255041ab330cc33520d13b1266fca859d8aba", size = 2514943, upload-time = "2026-10-27T16:30:17.326Z" }, + { url = "https://files.pythonhosted.org/packages/5e/38/7311ade45b67dc2c2a4f9d1af4c18285f92591235e8c6cab4f9cecd36516/fonttools-4.68.0-cp315-cp315t-win_amd64.whl", hash = "sha256:6aea5cdbc32f5fd202cf8dec053a784b08692f8b1992af80eba32bef82bf84c7", size = 2563334, upload-time = "2026-10-27T16:30:19.883Z" }, + { url = "https://files.pythonhosted.org/packages/8a/ee/fd08713d15bf0f6487a72e415e91ef4a6b52ca96fa8f879533107a41e18d/fonttools-4.68.0-cp315-cp315t-win_arm64.whl", hash = "sha256:b612613f0165f560571c4e372af0ebbb1c4b36067de409922dcea349beb8bb20", size = 2528487, upload-time = "2026-10-27T16:30:22.222Z" }, + { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" }, +] + [[package]] name = "harmonizepy" -version = "0.3.2" +version = "0.4.0" source = { editable = "." } dependencies = [ { name = "numpy" }, @@ -228,6 +380,10 @@ dev = [ { name = "ruff" }, { name = "ty" }, ] +figures = [ + { name = "matplotlib" }, + { name = "pillow" }, +] [package.metadata] requires-dist = [ @@ -249,6 +405,10 @@ dev = [ { name = "ruff", specifier = ">=0.4" }, { name = "ty", specifier = ">=0.0.72" }, ] +figures = [ + { name = "matplotlib", specifier = ">=3.8" }, + { name = "pillow", specifier = ">=10.0" }, +] [[package]] name = "iniconfig" @@ -259,6 +419,116 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" }, ] +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/9b/65b302742389c6f96f2956bef5decf26011309feb2fc5d79613af18adea4/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:63fb7294b768f444eb4b068965f2662f28c2fd4161e23bd60fcf3ff27b74c046", size = 123876, upload-time = "2026-08-28T10:25:27.44Z" }, + { url = "https://files.pythonhosted.org/packages/71/74/c21f339956f6f691b2ed7e31d5f3ae767304df6c460192739fc830853051/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ebdef3eae5336568147c39a55be6a2036ffde53faa9ca2d978989ae7c2da12c", size = 66487, upload-time = "2026-08-28T10:25:28.728Z" }, + { url = "https://files.pythonhosted.org/packages/84/e5/bdb34e21523e01dceda064d63713f3bdec91388af24fba1eca7ea5e85864/kiwisolver-1.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1798e83840c3f627246104c4d8a9639c60fa068adf9ce92b61791781fa8a68c1", size = 64660, upload-time = "2026-08-28T10:25:30.071Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f4/dadfec469313c7f428efa7e84b4aba9732f813c13ea7131a24b7b008ef57/kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38", size = 1477929, upload-time = "2026-08-28T10:25:31.495Z" }, + { url = "https://files.pythonhosted.org/packages/6f/35/09c58daac34e6f6ea5c6dee0094b422118e5a7c265586008a95fd135ac5f/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d27c2123977cb9269c30a49ba45f03a4323017ef693e19db4ec9dbe1299a3002", size = 1278499, upload-time = "2026-08-28T10:25:33.375Z" }, + { url = "https://files.pythonhosted.org/packages/19/32/739765e24fbad29d13f83e546ea4abc215a78cea9d677ca09025b027724d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6a797a1cefc8b9c93170db580337e1fe3d011ad18b1299943231279406342048", size = 1296677, upload-time = "2026-08-28T10:25:35.059Z" }, + { url = "https://files.pythonhosted.org/packages/df/32/03304d1010e2cc45e5b3b52cef7e43fed3a2a5cd6c87a89b4a88e1d85b5d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2551cf9917af48ee7c4b29cc82320489508cf96fd26a51f6fc124de661cd44c7", size = 1346037, upload-time = "2026-08-28T10:25:36.705Z" }, + { url = "https://files.pythonhosted.org/packages/3e/57/4c49377bfd274450dd72ecaa13eaac32ea804a03363e4d1db0c5aa999ceb/kiwisolver-1.5.1-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:38f6e0deb4d0a4615efe0c4efc5990b06ae450ab50a0b321c0b078b6d238c083", size = 988248, upload-time = "2026-08-28T10:25:38.299Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c3/38df144a08b6c5d75ca4504e5cc3141bb3bfef64c04f4ef48204f42711b6/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bfd1de989b3330420e29de39352f5c049905c9e3ee67233a50d550e3d652c148", size = 2228722, upload-time = "2026-08-28T10:25:40.038Z" }, + { url = "https://files.pythonhosted.org/packages/e7/11/3221838a89cd64d9b386353e000cd8a296069a20fbe3584507fdfd5bebae/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1209042a623ddfda5497e4066c7b77651dde8e1d3a9dd97599dc7e97f3b9b78c", size = 2325216, upload-time = "2026-08-28T10:25:41.699Z" }, + { url = "https://files.pythonhosted.org/packages/83/d4/075c219230697bb5db910d37262b9bacf880f92b4811a02ab81ed073a253/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:26e8268480be5061d509e29669d59103c067a26377a56491630ece11762e3858", size = 1977689, upload-time = "2026-08-28T10:25:43.559Z" }, + { url = "https://files.pythonhosted.org/packages/bb/08/1d219c3c2dd960983d0d4da623d916e9de6385df2b0bab3d1af0e9b8fccc/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d79308fa689fac89cbcfbd4dbfc80b5f95c54c5a7fd4d194be221f9d33d026e6", size = 2491443, upload-time = "2026-08-28T10:25:45.242Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d3/024208ec1079d273f1047468d1bdffbf38bb75b7b268090fd3a0301b9d9a/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444", size = 2295200, upload-time = "2026-08-28T10:25:46.984Z" }, + { url = "https://files.pythonhosted.org/packages/6e/7c/7b210498f9f92e1cd7855f260fa69ef056881087b199ee20c208f0e4189a/kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19", size = 70748, upload-time = "2026-08-28T10:25:48.444Z" }, + { url = "https://files.pythonhosted.org/packages/94/61/ef0daa157c8bb23672f7423e0d14c39db1dc6ef8ed47e6bc54c9c1bef3bf/kiwisolver-1.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:ad8b9671348d7c8716715652ae11f85ed0eb99e265a2df2ca490577d69860b2c", size = 68324, upload-time = "2026-08-28T10:25:49.81Z" }, + { url = "https://files.pythonhosted.org/packages/08/c1/88018321d976f53c421e379c43bc6993e70ce0c8a3ec5edc4bfe102257f6/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b6ae6a0328f0bc035741820fdeecdcd67bf4694eee03972e843663107122f450", size = 62272, upload-time = "2026-08-28T10:25:51.02Z" }, + { url = "https://files.pythonhosted.org/packages/85/d2/712bc17ea4f1d216034928069d612defbc6c95a471c55a7203a39faecb1a/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:886fc26012f0e8b5f69d1cfe6d711f6b11f194621539bf8e6bb1c25c5dc82724", size = 64481, upload-time = "2026-08-28T10:25:52.22Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e6/6c5380d676f43b6d918033962ea5e72360ca69e5a404154bc496b598ffdb/kiwisolver-1.5.1-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aefe930d113798330e9462f7874542977869c0613cba3262e2de3a8d5dee8f3a", size = 66260, upload-time = "2026-08-28T10:25:53.387Z" }, + { url = "https://files.pythonhosted.org/packages/92/6a/7087f5822cc8bb272679641404b1966a42504dac9ee74e2b33840475a0aa/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a5ca5aebae78a0bc13c1943af4af615d4966c5b650b05d5aa83b50e427196fee", size = 123876, upload-time = "2026-08-28T10:25:54.644Z" }, + { url = "https://files.pythonhosted.org/packages/5c/4b/9f385087ca09ee5ab9c09c6832561a7d2f7c78d3e5661d511e669f70e439/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ed0f5e49d0ceff8b72190824d9e59c062fbbc02c231b853112c78474b3f5ec2", size = 66487, upload-time = "2026-08-28T10:25:55.899Z" }, + { url = "https://files.pythonhosted.org/packages/47/8b/40d33ffd2f378094ed462e9a9a0907e59d4de9845e65a59561272da350d4/kiwisolver-1.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:77a4c8187a5948d7f8795adb765a3c7b553d07d86d88e43038fc32fc1fb9a3f3", size = 64673, upload-time = "2026-08-28T10:25:57.048Z" }, + { url = "https://files.pythonhosted.org/packages/ab/43/86aacc027959108b4c66eeae8b73cedb057dfa6eb3a335d05ad65197081c/kiwisolver-1.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:74ad5c3dad54a4641b4c28cd15ded70899d04459c6c7aeacafea716be97cce6d", size = 1477992, upload-time = "2026-08-28T10:25:58.479Z" }, + { url = "https://files.pythonhosted.org/packages/ed/40/b1d0369048c79733a32c8abb0f2718532e6630641368e33a81384246e844/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e46b23a2da695c364124817bc01d970effd5483147f8d66a6a7167e3f6b851", size = 1278821, upload-time = "2026-08-28T10:26:00.121Z" }, + { url = "https://files.pythonhosted.org/packages/61/a1/fa71c1792272ff9461432715ae60ffb7e11a4d7ac3bf68961b9cab6c60cf/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:75d9b1cf8258462dbdc1eeda718c96ea7f079324c09067f6daabfcf37712b7fe", size = 1296805, upload-time = "2026-08-28T10:26:01.868Z" }, + { url = "https://files.pythonhosted.org/packages/a3/49/3f0bd94af8e06ecc47eb834b195a06f05d48711ceb2352c56d6835160f0e/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fca690b00c4c48f6c2a547b0160ed511357093a4e4c9b47e0fadf3128066d89", size = 1346109, upload-time = "2026-08-28T10:26:03.59Z" }, + { url = "https://files.pythonhosted.org/packages/a4/44/3afe6ef9cf06d61220953a8963e94eca978491be1d9547cb01d82a1efa08/kiwisolver-1.5.1-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:876bbfd276473d3daffe30e8c975df4ed9429967b41a6cb362dbb5155b6f13ad", size = 988252, upload-time = "2026-08-28T10:26:05.306Z" }, + { url = "https://files.pythonhosted.org/packages/e4/30/a12bd7a7285a211e1747c3eec77b8c614dbfcc1dad942f7611a1a6921ae5/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f942903fde7363d1d879057ec5de01310efda2597161784d752fa9953a01a71a", size = 2228846, upload-time = "2026-08-28T10:26:07.312Z" }, + { url = "https://files.pythonhosted.org/packages/a1/6b/233e2958abf0dab7b18d07e52f286e02e519d7651bfbbe97af9347564109/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c90d3022d8a94778939cda8638c6c8da8fa757b8958dad7ec868ce29c87681b8", size = 2325583, upload-time = "2026-08-28T10:26:09.093Z" }, + { url = "https://files.pythonhosted.org/packages/42/8e/7673060a27b01405b580058510adef34687069d229800239f5e44682d4d0/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:8a34616dc2521cc8dc1d7d081734da63539f021ac0450ce950908340c6e7aa2f", size = 1978221, upload-time = "2026-08-28T10:26:11.127Z" }, + { url = "https://files.pythonhosted.org/packages/3f/7b/1b882fc1a8b4a0bb8084e7d1d85004116d08c92c0705d31f2928dec607f2/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:8bf4df63592c2a66b4f8edc5df2544998c288aa02f96ce0acd880cd1de8c8127", size = 2491819, upload-time = "2026-08-28T10:26:13.348Z" }, + { url = "https://files.pythonhosted.org/packages/39/9c/426deb49e62c5f69464b64bbeca064d3b758a7506b8913d986ef34f4619c/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d09037ca068d784ebc4aec290ef952ca27ac15dd9c0b5801a88c6e1096b83e6b", size = 2295520, upload-time = "2026-08-28T10:26:15.042Z" }, + { url = "https://files.pythonhosted.org/packages/f5/22/deabbb3ad6d918d74b7831b2d8ae7151b09d21c87974e5ee8a456f58c94c/kiwisolver-1.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:dc23390afe9f4ef9ac3bcc72a03a56eebbde03f4c571a32cb38f859cff9a6524", size = 70758, upload-time = "2026-08-28T10:26:16.504Z" }, + { url = "https://files.pythonhosted.org/packages/b9/71/02fa5c2fd92068bb8952847e70ee6c5cb280e7febe11653d17812acc53dd/kiwisolver-1.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:186884a58486651e3c217b6acea0a53eaa9498fdd472057c46f2f0fb5c25aad5", size = 68329, upload-time = "2026-08-28T10:26:17.658Z" }, + { url = "https://files.pythonhosted.org/packages/dd/87/2d5dfad0daf17dcc18d98c48ed2332fc3f051cf599e60be6182a30dd4cf1/kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0324cd2567259b7a095f6cf18a52b0ffc6f3de9e69528ff1bc0e7a37bd43ff1a", size = 62337, upload-time = "2026-08-28T10:26:18.778Z" }, + { url = "https://files.pythonhosted.org/packages/08/c8/83e1624f15d6262b470dbcc80b09979fd4d5b2ea3ddfc6b6e3327e235726/kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:74ea337e0ec3f6f342a36a4f1b5cd94dd9affddcd28ba9aae2905af932ee8c6b", size = 64513, upload-time = "2026-08-28T10:26:19.909Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2d/827ec30eb07f528c08d8459ffb318ae91a56d793ee8acbea8b491f0ff906/kiwisolver-1.5.1-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ee9df1f0d77b9c6e94f4ac0fec533fbddd5ea3a327807f18d7b069ae019ded80", size = 66287, upload-time = "2026-08-28T10:26:21.078Z" }, + { url = "https://files.pythonhosted.org/packages/53/11/5c43a562529dad8def4b81e5e1877c612a7e0298105a5939b3b409d2079c/kiwisolver-1.5.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fc271a6f0a2126958f4090e5507b9da5848927dae331f8f763bd4aa642b3d2cd", size = 123940, upload-time = "2026-08-28T10:26:22.475Z" }, + { url = "https://files.pythonhosted.org/packages/64/db/9bd6c505c95128c258a55236bfbb3a7a3fb6023f863316b6d7d9f3c69052/kiwisolver-1.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9b3092d8992a1d69b7a59c3e39f35e1b9be327a17f68a7c35fc17329e337d6f2", size = 66493, upload-time = "2026-08-28T10:26:23.743Z" }, + { url = "https://files.pythonhosted.org/packages/e1/f4/b3007a3ed5c9be73f81161140684cf7d9bdb9c4b632f5f484d2a1c713fb9/kiwisolver-1.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c2306e8bb53601979fcb3fa09cc65e031876d9ae01eff2fcbcd7a84ef94d5bc1", size = 64720, upload-time = "2026-08-28T10:26:24.95Z" }, + { url = "https://files.pythonhosted.org/packages/a1/13/08188f0cafa3a800403e4ff62b9aad4e7a17f9c4c7e080dc8f18c64794cf/kiwisolver-1.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:18a0cfb124546a4c2e6087c5f3029c7f44b37c85b142e0ced71f73a7599ac208", size = 1475867, upload-time = "2026-08-28T10:26:26.393Z" }, + { url = "https://files.pythonhosted.org/packages/8a/3e/053bdc3c9abdb8f2606225eda398adca25c0c91ab90add8222a69db65ee0/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34ec467940442c9943016fb2d4c81d1ba84351eeca2f1a78f8bc87f1ba0d414c", size = 1282865, upload-time = "2026-08-28T10:26:28.118Z" }, + { url = "https://files.pythonhosted.org/packages/5e/64/a44c341b36b610588cc2f1e89b3cae072a3119aa8be578e90987cd640751/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a83ee7107df13abe42a54a6654670eef9bb39425cf2e27f65e0007465e1286ab", size = 1300865, upload-time = "2026-08-28T10:26:30.125Z" }, + { url = "https://files.pythonhosted.org/packages/60/5e/7e7d716dca38c714478b741257a5b4a321d9932b8d851551a136dcaf3984/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bebb89489b279b2f5661bbbb2abcc87bcd4a46607bb4a5c966f04f1db6b8df9a", size = 1348071, upload-time = "2026-08-28T10:26:31.829Z" }, + { url = "https://files.pythonhosted.org/packages/10/1a/2b98fdda8bf45b7be317e48ed12393d44334394d315c74b81f4a14c0e31b/kiwisolver-1.5.1-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:509735237ae0d849e8a843551d423d2500d2e0a9ac1611a145658b29c0fb9f85", size = 992191, upload-time = "2026-08-28T10:26:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/b6/55/d893f5ede0e50f9e3fcf01f6015f42ec7d9cd221e26772701fe4a98745f9/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:824c3d763a05ea9e9003610145186b0e9848c7584a5575c79bac5a8e7cd80bad", size = 2233854, upload-time = "2026-08-28T10:26:35.282Z" }, + { url = "https://files.pythonhosted.org/packages/b1/82/f85f6279555a6ee1639fef7bfe83adb037a03e11a6fc9eaa54b8d0380339/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:1fff05e239575b1481b6ed1a782f6fad616efbf1f0b1f44e6e85c4dfe426e483", size = 2330621, upload-time = "2026-08-28T10:26:36.9Z" }, + { url = "https://files.pythonhosted.org/packages/56/31/e11aea078f66fc2fffcc179d38ca90d9da97652a241b64519169742ba46a/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0627b9bceb9c3cdcf12b8a18655eedfed2692b038df27423383c120d0b7dc2d6", size = 1982848, upload-time = "2026-08-28T10:26:39.01Z" }, + { url = "https://files.pythonhosted.org/packages/af/ea/2956b63bf5140ca46aa2c2818e6aa03e2d5754dd2fa41db1c6b28922940c/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:8a708a47ade1fe19e8371d5da076bac0dd4b0a5a7985ad6c637f7f7e361b6baa", size = 2494850, upload-time = "2026-08-28T10:26:40.837Z" }, + { url = "https://files.pythonhosted.org/packages/11/d1/3829542258d8b3fc0898d221e7ef0e2c83eca0d348709bb8dbe54f3d4005/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:007a5553dfc4f4e8d184f588a0200e2cd4b63a59cc8796df3c39909e679dc7a0", size = 2298067, upload-time = "2026-08-28T10:26:42.803Z" }, + { url = "https://files.pythonhosted.org/packages/4e/0e/49522e1ab5788cbaf63a26fbd3b851f9028616828c961b8a31b35cb96df8/kiwisolver-1.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:f4167e87b397f273dc2356fcf1eaf50a6bac51e6105f45103ef7129c8efb0255", size = 72282, upload-time = "2026-08-28T10:26:44.268Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b6/22e7ca5315d363e6f81c9f37c9472e12e7b298731e77c0428e6a911a2c39/kiwisolver-1.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5c490db2168a508088f59140dd392556a54b8bd1048fc6383c8baff13c359673", size = 69855, upload-time = "2026-08-28T10:26:45.725Z" }, + { url = "https://files.pythonhosted.org/packages/30/8c/03a9cfbe871964c8758a816eb03ac96c806da2795a9a7cd9bf9648bfb594/kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4d4ca09bf13cff792b1884f64b98ee6c2467930d632233be25c56b442d99f10e", size = 126289, upload-time = "2026-08-28T10:26:47.023Z" }, + { url = "https://files.pythonhosted.org/packages/f2/e3/14ce3041ca79dff9c9d884ca00c7bf32374e76028a865a9ecd99b4f5a517/kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:44b8faef94f1857e77fa0238f3390ff1ac51d2ea20a487e2e452a59fd2b5f5ca", size = 67709, upload-time = "2026-08-28T10:26:48.268Z" }, + { url = "https://files.pythonhosted.org/packages/af/c4/45030471a66ec8ef042e9f96ffe1d522c9ab12da180186a0898966fc1385/kiwisolver-1.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2ae70bc59790d2af72a3f76f24b272403e135070340281108b447cb77ea70819", size = 65909, upload-time = "2026-08-28T10:26:49.523Z" }, + { url = "https://files.pythonhosted.org/packages/42/73/17dce073a6ae259bb32cf9d686c4079d2e538868bc45967462bf33df914a/kiwisolver-1.5.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:43844c1a7ad6d723d5b5b4c4fc7f5bd399c40e288120d16257c7c9e8765c6e85", size = 1584907, upload-time = "2026-08-28T10:26:50.933Z" }, + { url = "https://files.pythonhosted.org/packages/8c/84/ae3c75909f507283cbfcc7e916c7e822579ef962020b97e6882b27b4478f/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22d5e5aaad6be121f2515765e3b1c444352cb8eb4c86510801db8f2e50757316", size = 1392474, upload-time = "2026-08-28T10:26:52.638Z" }, + { url = "https://files.pythonhosted.org/packages/34/31/8bcc83caad5bce8fa4577152389848bf6bc110e51e573a2b4e7c2aa34c89/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3fa5855898f6d3d01b72ccd48a2d65cbdee301251603fefe34e2025bddba219c", size = 1405246, upload-time = "2026-08-28T10:26:54.248Z" }, + { url = "https://files.pythonhosted.org/packages/55/72/220345537d790cf4ae54f8acfff4b5cc2468e0702a384d651cf7a771c63e/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d66a64dd5dec136040ec2ae94aa026a912ee60fdd45bc28d3db30037fd809e88", size = 1456099, upload-time = "2026-08-28T10:26:56.042Z" }, + { url = "https://files.pythonhosted.org/packages/cd/10/3725fd2398f66d18c34b4e0f81a8d03764cd4f4f089f58a527f0b4428086/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:9e51c119992ea8820706871c30a4642ec76de20ae82f9b50b9a45517d8e9f810", size = 1073695, upload-time = "2026-08-28T10:26:57.658Z" }, + { url = "https://files.pythonhosted.org/packages/86/cb/28d6e09e66b93e4588b2e6b7d84d020ccefea09e2f4de788510a07efeab7/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:70ed9a45c7484d2b30cdacf60d220f494a1763b9fec1ad03285c6553fa0889f2", size = 2335355, upload-time = "2026-08-28T10:26:59.202Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b3/a0f31d5e4e40af7dc97c36b8a74fdd3a36cf3c8bbd098da9a23466ff6a94/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:98b208a7cc42c803445ef551d6753cc42a5ea13e9cab1ee66cd8b9cb70195330", size = 2426524, upload-time = "2026-08-28T10:27:01.181Z" }, + { url = "https://files.pythonhosted.org/packages/2f/c9/728f63bd58c72cafdc79fc306abeeac7391bec03b757a48dadeb30906521/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c6834b92dd2428e2dd85ef3d85f723d3c12f20aaf43a2ddd4f944ca25d833408", size = 2063430, upload-time = "2026-08-28T10:27:03.06Z" }, + { url = "https://files.pythonhosted.org/packages/84/df/ce188b96f92f9a2c958231da140768918cba53c9713dc887b82f85462118/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:5d142e352eb13facc7dd047489aebdff6ba78576c239f1ea04931979caaf0567", size = 2597513, upload-time = "2026-08-28T10:27:05.072Z" }, + { url = "https://files.pythonhosted.org/packages/69/d6/76947c8203768968382e5bd74d9cc95654746703a61ea53015f2c74a2e06/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f9b1c4900736e489a812c529100de4b8fb617d4db075e931e213c57424b83d9b", size = 2394488, upload-time = "2026-08-28T10:27:07.423Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d4/14b21e4eb203c4d15425e8b6a2c625a320b4a1f2f7557eead63ffc30ffb7/kiwisolver-1.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:5978c3340f16a35c30f8ab2fa7bcf559973c55f1a5ef6970e1f621acf3c4db13", size = 75404, upload-time = "2026-08-28T10:27:08.892Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f5/53157899fc7f45f76421b77b99eb1639dd0f83f26ff9d76300c96bb4a3b0/kiwisolver-1.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ca307d6c259e5c98d3cb9ade55342b47a6839762caf2536f3d7b46ee660cc82e", size = 72946, upload-time = "2026-08-28T10:27:10.944Z" }, + { url = "https://files.pythonhosted.org/packages/75/62/f786c3a27f181fa339d851a77e266d208e776b9883cabc40a5b041a31b5a/kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:bb7c99f0673c03017a3ee01e54a5c2617a05468b11eabe513b0080e063ed95b1", size = 62420, upload-time = "2026-08-28T10:27:12.308Z" }, + { url = "https://files.pythonhosted.org/packages/02/cd/58a91ed25fbad0facdf503297b03768efab04bdf3141e5e3b49a34be7443/kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:0d8924877ce22e17326a99a418c3c82037da078df3c6a260b13eca677444e6e7", size = 64577, upload-time = "2026-08-28T10:27:13.502Z" }, + { url = "https://files.pythonhosted.org/packages/f6/5c/d501ef5a0958b226eac28306d24d5e5f114be0ace50e19cabae7b6b3b197/kiwisolver-1.5.1-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:534f02c1abb31ed6dbd3515545285c330b2f12d00fdb1fdb71658b9ca5a13a6a", size = 66284, upload-time = "2026-08-28T10:27:14.813Z" }, + { url = "https://files.pythonhosted.org/packages/a3/a6/8fbecaf4fc18c02f31f05e47a84c010a80e3ec391ed2f0bdade1d62b5954/kiwisolver-1.5.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:cea20da04494e662b83c872683bf4ff2345206043d036315ed0e924b652e7294", size = 124031, upload-time = "2026-08-28T10:27:16.193Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c6/bf3090d2983b4204347cbdbe952116e7c3b2abf62b4e33e50167a13e75ee/kiwisolver-1.5.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:7fd82debf43c6acd0a94359d232f6bb516ee13f269a7993736a9ac9f988bb5d9", size = 66489, upload-time = "2026-08-28T10:27:17.506Z" }, + { url = "https://files.pythonhosted.org/packages/85/de/562dddef55fdd7c291da8626d6619e72b5fc0870e6ccca0e149a5731e7f3/kiwisolver-1.5.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:18170a77ddfecf40ec60d0928268dc95880c881864e015a8f34094ed18b9b9ad", size = 64806, upload-time = "2026-08-28T10:27:18.673Z" }, + { url = "https://files.pythonhosted.org/packages/89/b1/ba7b9c0164ce1cf62bf2872db63b8483289cf0f3110d6f9390eb09e409ed/kiwisolver-1.5.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ca7f6fe0f37ca978a1e5eb7a3a68e6413f417e78e838324947ffd420202b198b", size = 1482211, upload-time = "2026-08-28T10:27:20.039Z" }, + { url = "https://files.pythonhosted.org/packages/13/dc/34da54efb4976616d45c20aae32d70e89d6e7395ed908029154d1609ef22/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5b973887ff782cfd6b67c9904ad8ca542e0bc5e4961503408b423b5a688b4d38", size = 1283739, upload-time = "2026-08-28T10:27:21.82Z" }, + { url = "https://files.pythonhosted.org/packages/5a/3a/30ffb62bee646e266e98a1b5cd276d9c75b6116fbfcb87c1190838c1b6df/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f76fc85bd054c806960f917ec0f329e24e436f1712267d90588e4c39890caa63", size = 1301681, upload-time = "2026-08-28T10:27:23.876Z" }, + { url = "https://files.pythonhosted.org/packages/a9/8d/13c70be22a8506880b35fdc38dca36629613bc493405c79f4037f2cd2bb9/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:828f75af2b0080c8a972e75f649ab46af008e92c6104a57a759157200b835b75", size = 1349159, upload-time = "2026-08-28T10:27:25.899Z" }, + { url = "https://files.pythonhosted.org/packages/82/0e/993972b8ec6767f47cd69818fb3a5ff14510557d29f7d1a839be7574fa1b/kiwisolver-1.5.1-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:431dc224a1a92a5c8f582d96e505196a3b5997a7271076678da2dfde67b77e9a", size = 997613, upload-time = "2026-08-28T10:27:27.507Z" }, + { url = "https://files.pythonhosted.org/packages/36/82/ca26eddd2eda2420dfc56693449c1f821f78b485da9cbde9904c03af3f93/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:61e9a64c7635095a6bfe483e2ff055d437c59bd45f3617a228b37277f0185d62", size = 2235109, upload-time = "2026-08-28T10:27:30.113Z" }, + { url = "https://files.pythonhosted.org/packages/c7/84/97d920881e10840b8d7c7185620298e3e4c88820b05514e3a15a258b08a6/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:3c24cd69455e1b00ddf770c13b6e2c33e07d6dc3f2d34add0bf9277c5c6bbd46", size = 2331207, upload-time = "2026-08-28T10:27:32.795Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ce/34d74b8f25acc58800f4c09268371e8d6159cf0f1206f1e4dc7835629b48/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:27add358abe374ebaa3b8763ef380bc99051b5a4b18d94878366a9e4f59efef0", size = 1986696, upload-time = "2026-08-28T10:27:34.628Z" }, + { url = "https://files.pythonhosted.org/packages/0e/01/f892644014612527aef7031d3306a2ffc60b3cb044f802c1561f8e5e14f3/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:255605693a483db7bd5c79f60437f7bf658f7f520d61aa42722e32257c941951", size = 2496400, upload-time = "2026-08-28T10:27:36.818Z" }, + { url = "https://files.pythonhosted.org/packages/32/6d/d8284e66e697026536e5f418b9cfe56567bffd3c775e3ecfbae373605854/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:7d38b0c279c3032e8c9cc013b405c6df8e1668dbf15465779aa7f15f61201812", size = 2302967, upload-time = "2026-08-28T10:27:38.803Z" }, + { url = "https://files.pythonhosted.org/packages/46/0a/69a355e27f32ba50d5b6369949b6a1702e122f5277c89bc76d452b81c1c4/kiwisolver-1.5.1-cp315-cp315-win_amd64.whl", hash = "sha256:958254518717542d02d0688d0d20cbf771da5e415e6f49543f92481c850a4540", size = 72283, upload-time = "2026-08-28T10:27:40.491Z" }, + { url = "https://files.pythonhosted.org/packages/ef/d8/7a95be90c33dcdd52204d4aa6384d731443225b887283bbd8b61e7931f6c/kiwisolver-1.5.1-cp315-cp315-win_arm64.whl", hash = "sha256:da3275833be0edbaf4830fae08bae3dc7219f40ce0c37eaa6c25825957e06612", size = 69860, upload-time = "2026-08-28T10:27:41.835Z" }, + { url = "https://files.pythonhosted.org/packages/31/f8/9bc493e7f5707788ba7f621902c68f82dc3a7ba03c78fbd337b026cef1ed/kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:470d420f98d368d6f010633a20659b544c5fdfa5329e6b70219f2ef08fd4a7ef", size = 126336, upload-time = "2026-08-28T10:27:43.379Z" }, + { url = "https://files.pythonhosted.org/packages/d1/82/3aea86b3f99712db825e9ac5631bf99571e818a8b8961ff98cebd798413e/kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:83f78128fa28705fa85d01c59771c72fe81c11bd0e6155edbb9f818983a7d761", size = 67698, upload-time = "2026-08-28T10:27:44.613Z" }, + { url = "https://files.pythonhosted.org/packages/84/7d/8daafc5d2e7f9c47a4f78f8865d86d2a9cf399c2a85f86c44a993594410c/kiwisolver-1.5.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:9506e892bcc3b409831d363c6f53e5985e1c8d1f6f6b0256d00358684ff85378", size = 65945, upload-time = "2026-08-28T10:27:45.932Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c9/51dc974d9130da70a8c47a96160123443d387ffe1b6b833d6f91d9429339/kiwisolver-1.5.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cea90547bfd93807e0013a004dc76552be44fad3bc1cc2b38610a9e889ed098f", size = 1588030, upload-time = "2026-08-28T10:27:47.678Z" }, + { url = "https://files.pythonhosted.org/packages/e6/86/f3e1a730e7a995149d8d3ff9e313b6d8a17b2cf1d98a8eff139dc30463fb/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8e4d953faaded9ec7ede36824e9814082d22d4c7b1eafbfa079ecba8cd0d076", size = 1390760, upload-time = "2026-08-28T10:27:49.676Z" }, + { url = "https://files.pythonhosted.org/packages/4f/3b/8ba25a2b5a0d2375e046f1b72de5179513f0be95aba6e7b094c89303929f/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e9c01d3dd7ceba4d1d436cc021d40d592466e40b9bc7f5d83dc4e98a5c9cd8c", size = 1403279, upload-time = "2026-08-28T10:27:51.242Z" }, + { url = "https://files.pythonhosted.org/packages/18/d0/278d5cb8be812740027d5ca0a7eda0c375488a88d6dce0fa60fcc2591ad2/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:37f801b5d7cc0e5a548921308e059fd2b057bb42972b591cfa3049f95423c4ed", size = 1454429, upload-time = "2026-08-28T10:27:53.213Z" }, + { url = "https://files.pythonhosted.org/packages/94/37/bcbab41063ec284c1d200efe5087cf087798c2f8916960aa8a20dd303290/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:e68e151428b5384f766cd25739bf77c7e4a3dc93b5ded7a12118d9fbfdf78ab6", size = 1073225, upload-time = "2026-08-28T10:27:55.089Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c5/ab79dcdf5ae28909a51210ae0a1c579e97ff997b3466414f0d04c0994583/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8f8fddb8e323bd6eee4e54e69a39243beab22689070f4c66b472c4cc88bb89d8", size = 2334335, upload-time = "2026-08-28T10:27:56.78Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/71d047468a189041d9c93f3b76844b924f9793b188c44bd149fa258912da/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:3cc210010fd2f438a3ed430b45f1b501fd13a8618bf984dc2c5ce5b69b78752e", size = 2424982, upload-time = "2026-08-28T10:27:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/7d/37/1347461bbea6d0e1f0580b94ef603b18e72c2be5f667fa1653867361a00b/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:b5664603a253efd3a75716d793d1d3a6a82723b61dc6db767b2460bbbeec4c0f", size = 2062857, upload-time = "2026-08-28T10:28:00.407Z" }, + { url = "https://files.pythonhosted.org/packages/1f/87/c7f0976c9cd0d127643351bc0c9929e0b8899d7f49d4ec238cd909e39c42/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:a7b85b2cc6ea45e5f7e8c9a30bc9fabd47cda09106cbb4b967335c3e6c43b69d", size = 2596022, upload-time = "2026-08-28T10:28:02.183Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9a/59a6f6ae6f938c15076be2c21b6cedea973d71bb1349ec84fa485fab82cf/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:ab620eb663952455271ac37f9aaad86b73c969c02f11f53cea405b38e96a4300", size = 2395634, upload-time = "2026-08-28T10:28:03.977Z" }, + { url = "https://files.pythonhosted.org/packages/e9/2d/8982c1fb7926da5bb7ed60318c3665b5c3f941447271ac982960a11b8637/kiwisolver-1.5.1-cp315-cp315t-win_amd64.whl", hash = "sha256:cb6fae641357ed2f6e533c0d3c6504a4a5703621a50c89459e46051d56b61140", size = 75379, upload-time = "2026-08-28T10:28:06.307Z" }, + { url = "https://files.pythonhosted.org/packages/07/78/ba7b6dfa1708b82b373ac056928a30c545d5c1a627df9839dcec3c6c1881/kiwisolver-1.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:b390aec180a7c054919c04898835e1c77bced23ea8383eb2c570213bf25d1a86", size = 73011, upload-time = "2026-08-28T10:28:07.578Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c4/1407df7512a5b36cc79840e01710dc575733c461b13ab866cae77eaf87f3/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:482676e5bd48d70ac99d9fc78863469845421e01184fa83f1f9366dc49f7e974", size = 134002, upload-time = "2026-08-28T10:28:08.881Z" }, + { url = "https://files.pythonhosted.org/packages/16/45/c37a21ad5c0ab581a93c55ad544721aaa1f0ae94edb29c6a678a23d013e6/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0", size = 194292, upload-time = "2026-08-28T10:28:11.06Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c1/69f00d627949580e43d57af0aa465df46868d7c29801c137a55374101294/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:a5a00665d1a0e26763a7338d7e911d4598fbc1d50dd0d6b7919b7dc6c5d6569f", size = 73362, upload-time = "2026-08-28T10:28:12.449Z" }, +] + [[package]] name = "librt" version = "0.16.0" @@ -360,6 +630,67 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/36/69/7a5d10ac409c4da0355e054a14371871da9b5557fcc42772cd00181c6cce/librt-0.16.0-cp315-cp315t-win_arm64.whl", hash = "sha256:8ceafb70f2a4f0826f11031942e59c0728fd98da112dc346d4352bde1e486866", size = 116391, upload-time = "2026-09-29T00:55:07.484Z" }, ] +[[package]] +name = "matplotlib" +version = "3.11.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/c8/9aa712a0afb882649424dd8de8ad9aa6235e796e84c6052e8f6dc1598d0d/matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4", size = 32660610, upload-time = "2026-09-11T19:05:31.214Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/ce/1bfcc4873b121597791ad74032943b123218c0613af0b97e8dd05e916fb1/matplotlib-3.11.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef752769cd962f39ea0b6ffc82d1ea43a0012c5a6157c7a075212fa509cfcff2", size = 9476466, upload-time = "2026-09-11T19:03:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c4/7f5f3601ee69baf072c0c7d3ce60c03e0618621c5a56c34a62a460e29d11/matplotlib-3.11.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ef31985c4dedb5f1424e1aec6849a47dd37689cb7fa3c20b1b82187f26806261", size = 9305583, upload-time = "2026-09-11T19:03:22.39Z" }, + { url = "https://files.pythonhosted.org/packages/b8/90/2b3fd67ee273163faeda6d514be70b5596eaa0fd77b60ffc294ad0b34f5f/matplotlib-3.11.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:df4f7784aca81a94f254c0a2767d592ee25f407e488f5fa7203e51093fb6ca27", size = 9860353, upload-time = "2026-09-11T19:03:25.049Z" }, + { url = "https://files.pythonhosted.org/packages/f4/84/32549e7a462dc311aed2ab62e5d2538028840b5c53a8be0195c789937c3d/matplotlib-3.11.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b9a7ad579856284135e401ecc918c5f8a017ee30539298862a109f51b971710", size = 10670348, upload-time = "2026-09-11T19:03:28.108Z" }, + { url = "https://files.pythonhosted.org/packages/84/39/02e21b74f7439bd643d717ea846006d46e309e6d29b632b57751265311d6/matplotlib-3.11.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3aa4b8516fd26659e4363abbf317c703d9116496c5db2e9d0609a2866dd39dd2", size = 10810580, upload-time = "2026-09-11T19:03:31.402Z" }, + { url = "https://files.pythonhosted.org/packages/04/93/0d239bde12b308262265c2d98909b2f0ecad2b5deeae96241642e822e9c7/matplotlib-3.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:c5c1c68ee401fc98271263410f0e5ce88285abacf7627132914e8adf3d70ff43", size = 9349409, upload-time = "2026-09-11T19:03:34.195Z" }, + { url = "https://files.pythonhosted.org/packages/49/a8/06baf901c02246c8a222b655cc4540ef9c15e1549a04e07927f9cde716c3/matplotlib-3.11.2-cp312-cp312-win_arm64.whl", hash = "sha256:643ff850d8e0f5b8319337f87ed3cb59506afb3df3cc48de777d85871233be7b", size = 9028084, upload-time = "2026-09-11T19:03:37.032Z" }, + { url = "https://files.pythonhosted.org/packages/bf/ce/fc58855a3d17f6cb8a87b6f9ccd100f65432a3a7ffed57309cbf14c78987/matplotlib-3.11.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7d43ff8cebb50840648cb6429b2228621dbd709010f3117b3740abb20abf21c0", size = 9476987, upload-time = "2026-09-11T19:03:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/a9/29/2a47b700545aca050e0ed73c89ba21e08407e11f5f42a567421b220de6c1/matplotlib-3.11.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2a8285cea8ef4d92aa041d1c33788bcae82248503300f93f1ca2136b9049452f", size = 9306050, upload-time = "2026-09-11T19:03:43.103Z" }, + { url = "https://files.pythonhosted.org/packages/a9/df/e7c10292f348cf55178a5b3c0092a38ea68891a3945f199ae8b7b8ac9dc1/matplotlib-3.11.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1944895967f87c84c9b4bad29a707b31f5b36df4a3a2339ea1f8ea3ce5105539", size = 9861060, upload-time = "2026-09-11T19:03:46.044Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b9/b978de6d43d47f1d4d8e653fac32c16d8d2e5f46bbbb822e26d7cb1adece/matplotlib-3.11.2-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af2661f6ac6bbd1d081996f54fdd9385715c625ace8cec0869055c0cfbf38981", size = 10670885, upload-time = "2026-09-11T19:03:48.942Z" }, + { url = "https://files.pythonhosted.org/packages/a3/80/d72f61bb2631ac15d17fada1f17e0f99fecba69d8376d34f17cf93b7eddd/matplotlib-3.11.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7e5a90f8a707ebb6004a713b1cff091a40cc5df4c7c1cb165e5a505ebc11c292", size = 10811222, upload-time = "2026-09-11T19:03:51.665Z" }, + { url = "https://files.pythonhosted.org/packages/94/2e/6d1d33f242c705b5c6c6fb3f0fc141add51cb1abb62912e59de0835d28c4/matplotlib-3.11.2-cp313-cp313-win_amd64.whl", hash = "sha256:bc067c462a86f0e57bf52fc6e058d90171a5420007dac00c46e90153050c69a7", size = 9349539, upload-time = "2026-09-11T19:03:54.534Z" }, + { url = "https://files.pythonhosted.org/packages/bb/bb/c0aa86a7f4c0e62f1c3c0711e361f6f23f87eb9018732a5e11994bd1b7ec/matplotlib-3.11.2-cp313-cp313-win_arm64.whl", hash = "sha256:3e8576f7c47e02fd4f21f44171302d2d1d58d4471d46da3d71fe8899d19539d9", size = 9028295, upload-time = "2026-09-11T19:03:57.261Z" }, + { url = "https://files.pythonhosted.org/packages/54/b4/4facdb700bc236e4c676495ca3798d8134ab8668cbfe0f6b2e9ebf962a38/matplotlib-3.11.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c9721f81275499da1feeb36a2cf8192ea086283b3bd16b7dc4c9d7aedb7396d6", size = 9478976, upload-time = "2026-09-11T19:04:00.12Z" }, + { url = "https://files.pythonhosted.org/packages/4c/a0/bba05f0a25bfeb0475c2f2a87958b31103aa6b7a5386017afb1a96212825/matplotlib-3.11.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a3040b209f3968b4e84161df7b174f07a9fad33b0f2d7e48ea3bbd3075e2863", size = 9307932, upload-time = "2026-09-11T19:04:02.976Z" }, + { url = "https://files.pythonhosted.org/packages/d4/42/81d5cba4bb39b41b0998efc880e129f2d7cdb94256ca49678fdcd9c21be5/matplotlib-3.11.2-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf3fe71fbfb8ec0e310e0bc8537c3405a01f38f25f9394ed2135e6202fed542b", size = 10674370, upload-time = "2026-09-11T19:04:06.912Z" }, + { url = "https://files.pythonhosted.org/packages/29/5e/52f56f93d5b20815ee0ae352f7a38eff25580edb180b4fa7df87cfeba68f/matplotlib-3.11.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8c8255de28f986d935a64c9ca71c0ec2d2f41d355691f5ea684725dc91413f71", size = 10954597, upload-time = "2026-09-11T19:04:09.948Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ae/f8918a1b564db49c53cd603eb3c8748c5767e4ce0fb2cf1d7c38653e4c5d/matplotlib-3.11.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a8756cc73d9af9a7fe0deb54ea2e75ef73b01d9e575877e72acad5458e660943", size = 10812583, upload-time = "2026-09-11T19:04:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/ea/61/4315ef0d63937fe56f451887b4a0be3b8e8b22cf1d92a8d157caac54570d/matplotlib-3.11.2-cp314-cp314-win_amd64.whl", hash = "sha256:ecea603dd2fbf8242fd31a305a8b12a4ece2de28096870c65fdd0d1e35b8d9a6", size = 9505972, upload-time = "2026-09-11T19:04:15.788Z" }, + { url = "https://files.pythonhosted.org/packages/d5/00/02398b0a1a62ef73d9af0a957fe1773363eec9a6ca7e433c72ae2790fbce/matplotlib-3.11.2-cp314-cp314-win_arm64.whl", hash = "sha256:01dc8eaaab5a9fce9ff615eca82345728f289e4715b186ee10c6d85272fc26bb", size = 9184534, upload-time = "2026-09-11T19:04:18.691Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c5/1e6ca10baa7e04f113c37856aadb4adc3dbb1c55fc7da6dc830bba1292d7/matplotlib-3.11.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79a258f58253dfa025af80a9e9bb228d75fced007f0e93ae7423fefbde81a74d", size = 9526415, upload-time = "2026-09-11T19:04:21.39Z" }, + { url = "https://files.pythonhosted.org/packages/e0/93/7561727af07ccc84747953c6a33eee3981cc436d04f465032e707ca0e429/matplotlib-3.11.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c0b83f044ce10a98027b105b3931548719a6e8c7ef986b4362651e0b5367c8dc", size = 9361064, upload-time = "2026-09-11T19:04:24.107Z" }, + { url = "https://files.pythonhosted.org/packages/c1/40/ce270ef2a6794d94a409fe28b8dabedffc07c07f9e5dbb89e0f605bd157d/matplotlib-3.11.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e43b188f0a5b75447bcc197728258166aa64365770ed1caa36595a5e1ca4bbba", size = 10684626, upload-time = "2026-09-11T19:04:27.201Z" }, + { url = "https://files.pythonhosted.org/packages/45/46/396e0307dbf1c1f2d0a3654caa6dbc780dd5379f5f11257369cf8d21d9fe/matplotlib-3.11.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3304eb5a59442a8867f6920d484591c0fa09ffc29e9260be2feec3351e25869", size = 10960602, upload-time = "2026-09-11T19:04:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1c/97/4defb84695477340aa88b27c9482cc1ca4de11f36f66b6c8c0ddd685def1/matplotlib-3.11.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:02329432ae5c6af87cf208ee575b701d698bdf0b1a3bb28cc6d53c36e967e575", size = 10822603, upload-time = "2026-09-11T19:04:32.964Z" }, + { url = "https://files.pythonhosted.org/packages/7d/e7/eab54551c1ec6b72dcd678a078b6c6da8d4c85ec1ff0016e81fe52866304/matplotlib-3.11.2-cp314-cp314t-win_amd64.whl", hash = "sha256:f2ac30cf5eb5dff1b584627ae0b0e1186551a4f69ae3c75073911da497a29170", size = 9551206, upload-time = "2026-09-11T19:04:35.811Z" }, + { url = "https://files.pythonhosted.org/packages/4e/0e/04698032cb4d8fb1e30d8ffec5ded20f6f582b03c8c58b2385c95245f158/matplotlib-3.11.2-cp314-cp314t-win_arm64.whl", hash = "sha256:cf41ecd1b0c0b6f7177ed965a54c2afbe888715c7cf6054dc12d53bc1494002c", size = 9234977, upload-time = "2026-09-11T19:04:38.972Z" }, + { url = "https://files.pythonhosted.org/packages/44/a9/ca827c184b87364378964e36e7c0ae23651d146fdbc4000635205490cf82/matplotlib-3.11.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:894a9cbbecbe30ae6787d464df2e8fc7a8d475cfc68f87c3029f7c11152899b3", size = 9478997, upload-time = "2026-09-11T19:04:41.914Z" }, + { url = "https://files.pythonhosted.org/packages/48/60/01aaafc9c3159f3fae9a65bbcddaa4a6d4d72b0aeffdd636d7f6d00a5c8d/matplotlib-3.11.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:bbf1062991d826ed27e2144f3afa4461afbb8ff56e8f703043e191a8163b1ee9", size = 9307947, upload-time = "2026-09-11T19:04:44.834Z" }, + { url = "https://files.pythonhosted.org/packages/1e/a0/6aa72c7cd7cf4dfac652744d7a3310007cec3ce8e5ab9be607bec7096471/matplotlib-3.11.2-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:399fef672f7046ef7d6a57572b2a6f9845f3f5afcff04e7b2df7a363a9f42190", size = 10674370, upload-time = "2026-09-11T19:04:47.745Z" }, + { url = "https://files.pythonhosted.org/packages/a1/97/d7e90225ac145046787a2ee0fa4cdc7e4d5cb6772ea232130b10f8a4095a/matplotlib-3.11.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc82dde2a0d3e3ad472edce04897ad7146b8d8bfd1df8a32992eebb81af18fdc", size = 10954581, upload-time = "2026-09-11T19:04:50.712Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/89cf056a9d2cae01f4b8baf01c7e809d613244fcdfa2a2acf28c1e0d79fa/matplotlib-3.11.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:930efb28f59fda124e39265d177bab302625297bb147d2910de725a2fc2aef54", size = 10812605, upload-time = "2026-09-11T19:04:53.552Z" }, + { url = "https://files.pythonhosted.org/packages/9d/4d/c61b9f4c34af802d4d84e58803e009013d626b5f468bafe1416131863b5b/matplotlib-3.11.2-cp315-cp315-win_amd64.whl", hash = "sha256:3da3bc0cbf7245e7db72cc6d29d12c5abef72cb73059c73b945f14e3545f3eb2", size = 9506068, upload-time = "2026-09-11T19:04:56.519Z" }, + { url = "https://files.pythonhosted.org/packages/03/7b/047f2fa8708d47430d8e7fa45e9fffb0aee5d4e300f978e087be2ee11fbc/matplotlib-3.11.2-cp315-cp315-win_arm64.whl", hash = "sha256:f25446b2981717dca9786bac841cb3fd7efb568e3e3c755dd980481c5cb9228d", size = 9184576, upload-time = "2026-09-11T19:04:59.318Z" }, + { url = "https://files.pythonhosted.org/packages/03/6e/ad9c5989950785a98642667df265a47c6637e924cb69b5dcf68c3299ae7c/matplotlib-3.11.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:fea03cf56568cc1cba08b470be6a0559e71c3a5b688d54b7179bb35ba23d0821", size = 9525988, upload-time = "2026-09-11T19:05:02.304Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c3/25c61701fb655dd412428b15eee2591ce554cdd593e39a045a153373f428/matplotlib-3.11.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:254d4ddb2fa8df3b4c689c0c306063aee10521df82cfb438185e499c75fe37c1", size = 9360774, upload-time = "2026-09-11T19:05:05.092Z" }, + { url = "https://files.pythonhosted.org/packages/58/5a/4552878fce8f9d249a5e264c16f5c267c27eac08fb039fa3e207a06feff5/matplotlib-3.11.2-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e60cf3047a51edecdc4535a9196bbd6a732936b8e9f8184aabf4d16165884aaf", size = 10685892, upload-time = "2026-09-11T19:05:07.686Z" }, + { url = "https://files.pythonhosted.org/packages/af/dd/b3b19ec0124fc4aafd8a4b3bae859c562a7ff0fd8ae3b2099947f78bde19/matplotlib-3.11.2-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eb3712dc9b464793de0a4e42a7313d50293c751f94bddaf7332a1bc71bccdda9", size = 10964946, upload-time = "2026-09-11T19:05:10.943Z" }, + { url = "https://files.pythonhosted.org/packages/7b/30/687ccce22f66a57fed85942450e88062773bcbf1a42914e70c7148ec71dc/matplotlib-3.11.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:75b6d88402770e181b5d06a67dda4129c31da7d05004d63a21c310ec78d1b83c", size = 10824960, upload-time = "2026-09-11T19:05:13.9Z" }, + { url = "https://files.pythonhosted.org/packages/d3/34/117fe35a8d05054b4b34d2d29287099927c24c3841d36e06d9fa2f20c1cf/matplotlib-3.11.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a6939df7567114b6bac7f4c5e06c84a67f197c1b2f2e4b234d4eecb3bfec9482", size = 9551204, upload-time = "2026-09-11T19:05:16.48Z" }, + { url = "https://files.pythonhosted.org/packages/63/5a/9f440e7bec8b80d0af2a65d1165b2f4e718982dad785531f62255d9ff19b/matplotlib-3.11.2-cp315-cp315t-win_arm64.whl", hash = "sha256:d480038c83691532ed52ff3147db51fa902fc78cb2d8349993a1cdb684435bff", size = 9233946, upload-time = "2026-09-11T19:05:19.063Z" }, +] + [[package]] name = "mypy" version = "2.4.1" @@ -588,6 +919,82 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/b8/58d79332229482eb0d27c82973850808c19d37e5bdc14443d3417bd373f5/pillow-13.0.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:67c8d44ad89fa7eb88de5d6ef6199b1e03dd24974f85a67639fc8badb801fe79", size = 5568643, upload-time = "2026-10-16T22:15:44.474Z" }, + { url = "https://files.pythonhosted.org/packages/39/4b/f2ed53d83aa44ac19599ac0a54897f867fafb95f406980d1e24083f8cbe3/pillow-13.0.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:fc481f742ccda20e9ed760b8f978dff50f2a4e9bc253ac167fb0a05b0783ef52", size = 4852329, upload-time = "2026-10-16T22:15:46.284Z" }, + { url = "https://files.pythonhosted.org/packages/3b/bb/9e30e8ed18c20800ee327a12107d5249ad8dc444867b3adfcc21654e3c71/pillow-13.0.0-cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8bf295fe459343bc6093c8e5e0df60bfa189e0fcb775a22e2c2488fdeccc6c0d", size = 6519309, upload-time = "2026-10-16T22:15:48.14Z" }, + { url = "https://files.pythonhosted.org/packages/e6/99/fdf65cc539e266ab93546c261bdf98411fe165c6e4e13f9dbf597097192b/pillow-13.0.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:42d63be3af4f9b951b199b0a9d23365d37ab14687e6d77b74940432c8515c4ca", size = 7144542, upload-time = "2026-10-16T22:15:50.093Z" }, + { url = "https://files.pythonhosted.org/packages/26/9b/f38b7c4d8f599537e2d1a6d546cec9beef7536ff8f5c49a3f9c78179d8ac/pillow-13.0.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:4bd024d567eca931b668978d672dba914d4b8e2628e2c3073a2ad178de8a2620", size = 6618042, upload-time = "2026-10-16T22:15:52.054Z" }, + { url = "https://files.pythonhosted.org/packages/a8/7c/45ee28531f89ee4582967d8a17f7a26d71ca64cd902b93c269590cd60a00/pillow-13.0.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:23edf4ec4b6f4f240e8df6e4985e9ee2ced86474632433e55fb1e2548744bf40", size = 7228137, upload-time = "2026-10-16T22:15:54.009Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/9c2a969cb1b70201d04fa17fd5aedf02a732870b8da86bceaaa30b0ca385/pillow-13.0.0-cp312-cp312-win32.whl", hash = "sha256:02464da86f561f410e13b061ec37c3068a9cb557a095494157742d07b3c24a27", size = 6515423, upload-time = "2026-10-16T22:15:56.25Z" }, + { url = "https://files.pythonhosted.org/packages/ff/cd/73a79ecdc822076002eb24b5e1e4a530b0bb5310fcb6d239abbec877110b/pillow-13.0.0-cp312-cp312-win_amd64.whl", hash = "sha256:ff3fe9eb621fbb9db4c4be33ab946f6bac5f98ab50ca8d3260503653656c961b", size = 7272166, upload-time = "2026-10-16T22:15:58.597Z" }, + { url = "https://files.pythonhosted.org/packages/4a/a3/be5a1236efd085b3984e4305da8f179ae9dab80c991d2ad78f2bd5c4c843/pillow-13.0.0-cp312-cp312-win_arm64.whl", hash = "sha256:c3bc8ee0271387e0b1e3ad0ff893645990a656e79bf9c42f4f734a3642b11d51", size = 2698943, upload-time = "2026-10-16T22:16:00.637Z" }, + { url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" }, + { url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" }, + { url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" }, + { url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" }, + { url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" }, + { url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" }, + { url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" }, + { url = "https://files.pythonhosted.org/packages/8e/45/fbad9c7f5e2f1745c373a434d46072bc84eddfefaa28b852425ac957fda6/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:44629d4498c9cb6b2051806155f22141df0d8a929c56134b166655232dfb2f8c", size = 4190721, upload-time = "2026-10-16T22:16:27.524Z" }, + { url = "https://files.pythonhosted.org/packages/a2/bf/2074902a259a90692c5dbf132885d21671644cbbd3f690047516243a55db/pillow-13.0.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:bf97ba1b5542050e9b0c74e632323b6d8136cc99d64e193abebee22fe6013c76", size = 4290236, upload-time = "2026-10-16T22:16:29.562Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a5/3d1bb93b8ea38d15d21356c1b8e9f50971ac592aaa248f7fb71739094c0e/pillow-13.0.0-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aa694c49787040943570d61c9b8fc01271bd2a2cfdd55f0d896f8aecdce1a981", size = 3723093, upload-time = "2026-10-16T22:16:31.249Z" }, + { url = "https://files.pythonhosted.org/packages/84/a1/be060135d85187b25fa8b2573786c0e45c62ae27527fff5257675eb97f4a/pillow-13.0.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:49c12af515073e9bf511e4ef736743bf70d531a643668722279314b937742ba4", size = 5572253, upload-time = "2026-10-16T22:16:33.103Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f4/0bf6f1ac9ba7ee2ffe9914aeb410a1035a0c1a3c42f122388d7fc950bc4b/pillow-13.0.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d9b0a2bee3f3e03e9f29057aedb807dbf1e1d96ee1b9d0f422d9db6c8583271d", size = 4852269, upload-time = "2026-10-16T22:16:35.102Z" }, + { url = "https://files.pythonhosted.org/packages/83/16/b603274617b3e6728da3a0133d4fba1ea8d7fbe0c4ea5fef9cbffa398b8b/pillow-13.0.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5933fcea5a5ba64c686f55c886a115cbfd92f2900460784a1e79909fdbafd7b6", size = 6516058, upload-time = "2026-10-16T22:16:37.228Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f2/1371707ce438ba9a43f9d24089828494ec6f9396e28cd7903aa704dd6306/pillow-13.0.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e91c2b1cbeae768c98752e67e717e283d68dae45717b41f2d91eaee648e37b7d", size = 7142574, upload-time = "2026-10-16T22:16:39.172Z" }, + { url = "https://files.pythonhosted.org/packages/b9/a9/62cf68587f910bc87c5951bcb6e9430c7643a65076adf5f18b4bf350e2bd/pillow-13.0.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7f6299e494e46253d40c34653cac369412f44ca53b5f85d848d3f95b1ed0546c", size = 6614295, upload-time = "2026-10-16T22:16:41.117Z" }, + { url = "https://files.pythonhosted.org/packages/6c/c9/9e9b48178649730299be0bafbf5f810a5b6977538f5a92d47e4ba5f5d608/pillow-13.0.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:f9bd7d260d986f3553518c5d723544346fa48031f8aef3265d786aeb59845bc0", size = 7224841, upload-time = "2026-10-16T22:16:43.118Z" }, + { url = "https://files.pythonhosted.org/packages/8f/48/c44e91384b1b6c072a714a63d00608acc16a6a968735e478e4be4384e5ac/pillow-13.0.0-cp314-cp314-win32.whl", hash = "sha256:2e31c4e68cffd7b1f116127626813b82fcba19edf6b940a7b0c266d6484d0055", size = 6508694, upload-time = "2026-10-16T22:16:45.883Z" }, + { url = "https://files.pythonhosted.org/packages/50/e2/7ad17747517e4c813dca78257d6bb593466f8231baf1384bc98d92745edb/pillow-13.0.0-cp314-cp314-win_amd64.whl", hash = "sha256:f7cbb7a64e7ec664775195e4f81923bc8a93d9451b963f844e59118f63147a7a", size = 7281830, upload-time = "2026-10-16T22:16:47.725Z" }, + { url = "https://files.pythonhosted.org/packages/41/9f/e5b51f2ce8ef4563215334035403ce61a244f93a2e65c24a940131618f87/pillow-13.0.0-cp314-cp314-win_arm64.whl", hash = "sha256:a6aaa7871aebca081eb5c45f83e845bbd9712ae99fa9286dbfdcee835e63f4b4", size = 2695468, upload-time = "2026-10-16T22:16:49.515Z" }, + { url = "https://files.pythonhosted.org/packages/97/73/a53502f731f6c84805a4ce87a8881e86d07a65aee64728b900d112dc703e/pillow-13.0.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7b999816b5850a35ada08443e6e03945f1f6488144a83afe2d37b240a552aafa", size = 5578196, upload-time = "2026-10-16T22:16:51.291Z" }, + { url = "https://files.pythonhosted.org/packages/21/50/7e949959a56b5559c78ef172b70fc6025706acb289f3f648a15329e4fa6f/pillow-13.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:67871a13cf47275201553b536c025da777f997fa562a19eb798af4ad4b97c18f", size = 4857276, upload-time = "2026-10-16T22:16:53.399Z" }, + { url = "https://files.pythonhosted.org/packages/c9/52/43ded0ac08e77e39d17bd6d894162572201b5e8fdc4a022b14c55a1960a4/pillow-13.0.0-cp314-cp314t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8ca8f69b7c77fa96dad99f8638c1fc4f1c0bed4acaa1baf7a3c31bdb80a0ab1", size = 6607008, upload-time = "2026-10-16T22:16:55.525Z" }, + { url = "https://files.pythonhosted.org/packages/0d/2e/4a57ed216d5bf877387cba4d44c02aa87abe51ad2e06404aa6b597c4da39/pillow-13.0.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6bce6a29c3898191f4c9998e4d4e8f69790caeabde46e54da4bc235ce5bde683", size = 7224281, upload-time = "2026-10-16T22:16:57.738Z" }, + { url = "https://files.pythonhosted.org/packages/5c/3d/2929b248e135752d63aaeabf53f6de797e905b7b6263f9c1e2adade20aba/pillow-13.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:816752a5ef76a80484c8c441c85593b7ea9304f6231fc5776ad1fbff7e773058", size = 6695600, upload-time = "2026-10-16T22:16:59.842Z" }, + { url = "https://files.pythonhosted.org/packages/bc/33/fb0da992cf084ed1ee6ee05e96b6191e35c351eb707ca2df874feb24ce47/pillow-13.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5bdb38ba220b61b4ec31dd1046dea6b016d3c6850a23f43ed8b58332b2fc668e", size = 7300589, upload-time = "2026-10-16T22:17:01.686Z" }, + { url = "https://files.pythonhosted.org/packages/bb/af/c30dd9ef6a3dce84ecb1b2393cac629047a32e66279056c6cb46c3ffd65c/pillow-13.0.0-cp314-cp314t-win32.whl", hash = "sha256:06903aac074d00c988e77a1fc435286dc498506d4ca8d6f69df9babddf4ecc15", size = 6517204, upload-time = "2026-10-16T22:17:03.722Z" }, + { url = "https://files.pythonhosted.org/packages/85/d5/ef3a8ae7609c8ab26570abf18194882534b480d245a9148b895a2262c004/pillow-13.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:9a635068d9793c7f0d929f39f18b58f1bd86c236e8e7b64167b86af9232ebca0", size = 7286695, upload-time = "2026-10-16T22:17:05.543Z" }, + { url = "https://files.pythonhosted.org/packages/84/3c/0861db0c69a03689ebe3e7599d35668a414deb5aaafd8255215e4e62e3d3/pillow-13.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:0d1a9cf7bc6917538b20f8d06b9ab2147e542f68849e96fc58eb66bdf6acc692", size = 2698098, upload-time = "2026-10-16T22:17:07.674Z" }, + { url = "https://files.pythonhosted.org/packages/6e/eb/e86a41962a3a31ad495a3d6a912d9002b01bba4a6fa71c28703abdca7f69/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7d5e097eabd5d4915c27ac9f6e9325bb1e01a7c94d7348b5c4451d3fc30e8521", size = 4191213, upload-time = "2026-10-16T22:17:09.449Z" }, + { url = "https://files.pythonhosted.org/packages/dd/04/7e7445e706afec84ef06dc25b2c77f9cecff242c23730c62928ad1089d4a/pillow-13.0.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:51ebb529fc5e8abdd55302f6c3f8943037348ec2384329a3e55677f69ae2fdfc", size = 4290650, upload-time = "2026-10-16T22:17:11.196Z" }, + { url = "https://files.pythonhosted.org/packages/46/85/d534089068ac40c0f61f650389a296c812eab745a8a733f81feec39ae955/pillow-13.0.0-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c87a04e7f152ee4db5dbe15f0bfa3fe628a1aeedbe66b81c43b87f52c813f9ac", size = 3723078, upload-time = "2026-10-16T22:17:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/ce/2b/00b5c3b401df538b5dbe311d3899730fae5ba1e21cb8b80a128887ac6747/pillow-13.0.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:20722cd5375533ad754053363a80b8fb30c79d37930a6f7228030e237ce3bd5d", size = 5572292, upload-time = "2026-10-16T22:17:14.539Z" }, + { url = "https://files.pythonhosted.org/packages/72/f5/a6b0610f946e9b54ae888ba7ad29d6e2f8d9b11f69e212d70416b7186c09/pillow-13.0.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:04a63720f79e22fd54d897c233a68314c50ca0603360f54ce2bd5db8f0f43782", size = 4852222, upload-time = "2026-10-16T22:17:16.521Z" }, + { url = "https://files.pythonhosted.org/packages/1e/d0/c0ff25bb0427ec70f32aac995453321fc3c4494a46c7292ff02d9d260b04/pillow-13.0.0-cp315-cp315-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:4f8db54177035a2b5f717f94475b74907e12a96dc74f6d487f3966b0a4694071", size = 6527349, upload-time = "2026-10-16T22:17:18.534Z" }, + { url = "https://files.pythonhosted.org/packages/85/11/e46fa0bcc0fc117f1eacc206b3d51f04d583fab328b4b740672d0438d83f/pillow-13.0.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8f36aa77f74b14a2103622b196402c71330e4e7cf4122ee45c854e9a01e0eecf", size = 7152873, upload-time = "2026-10-16T22:17:20.415Z" }, + { url = "https://files.pythonhosted.org/packages/7c/53/2bdeca705f3a58679fa9201233193c86a30238340ca29b3a152c3fcc719b/pillow-13.0.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:149a1c323ba366f90b48e6f1a6db6582eb50512df374588de56fc909abc0f0f3", size = 6626871, upload-time = "2026-10-16T22:17:22.361Z" }, + { url = "https://files.pythonhosted.org/packages/14/de/3829030f209722ade3753bb456b805a0e7f885cf885b483407365c82e9ca/pillow-13.0.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:e892354a424b1e82a78ba16785822bdd40de06f19446a3d4a28047df1a4f8932", size = 7236439, upload-time = "2026-10-16T22:17:24.352Z" }, + { url = "https://files.pythonhosted.org/packages/44/b1/67fc37388382bc036a74f04da5bb6fcbf90ec3ac1f45893e06176c373fd3/pillow-13.0.0-cp315-cp315-win32.whl", hash = "sha256:8e459b613cf31f8980f584387b4fe47bf08e076e288d61aa8eba1f7fd4ddbb81", size = 6508688, upload-time = "2026-10-16T22:17:26.314Z" }, + { url = "https://files.pythonhosted.org/packages/44/05/fdb6a79aee10861165526b41b7b440e36ee1ff58613b2fbefe3acbf06d4f/pillow-13.0.0-cp315-cp315-win_amd64.whl", hash = "sha256:d4737f50d23ddd11d6685faacbb9252887dde0bc7997127757247983d74399d6", size = 7281107, upload-time = "2026-10-16T22:17:28.198Z" }, + { url = "https://files.pythonhosted.org/packages/e6/9c/6c6f7dc2a566467baf121394e83de25ac287cffe34cc030726beb4be0224/pillow-13.0.0-cp315-cp315-win_arm64.whl", hash = "sha256:2310e2adfc13c6d457d7d0f2ffdd5c56a74a317650cf765887df8d515a647ac0", size = 2695513, upload-time = "2026-10-16T22:17:30.013Z" }, + { url = "https://files.pythonhosted.org/packages/23/16/e9120defdb8bff693b582d035312acc6f530cdc2bc5238a87f410efccd82/pillow-13.0.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:21c32061a5512dc13f87cc7303e120e4d77c2f70df89a35af0e3ce246e5ac57f", size = 5578129, upload-time = "2026-10-16T22:17:31.642Z" }, + { url = "https://files.pythonhosted.org/packages/47/22/76faf2bb2448f48a84cf894c1e2bb1090d7d2b1aa521ece131cb2f05d631/pillow-13.0.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:1c774b9c0ba0d0b356f71530677b39028878a2cae5a93e0a13779cfd17120f88", size = 4857428, upload-time = "2026-10-16T22:17:33.43Z" }, + { url = "https://files.pythonhosted.org/packages/b3/64/0861ea4e03c50b14af9ed9dd8b9f388ab42f445c623a9fcbab19aef7aa55/pillow-13.0.0-cp315-cp315t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:20822140c9a2ba9c5e42df342b0a892ab2e102fc0e3db967a133bb9ce3f898bb", size = 6612582, upload-time = "2026-10-16T22:17:35.415Z" }, + { url = "https://files.pythonhosted.org/packages/5c/20/cd1e9b3f60a9f3d5ebe46da36955c26004092a501f7f2c42f9fcc26611bc/pillow-13.0.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ffea6b2986a797c84b6d1d27d4f43e0b83c73fc16281a930891cd237cf0d08fe", size = 7230176, upload-time = "2026-10-16T22:17:37.362Z" }, + { url = "https://files.pythonhosted.org/packages/b6/ef/ffb0a2fc85690714fb7ac662956949645d57f15bf4426f520da361e7b6e3/pillow-13.0.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:05cd2cd39055d0b9650060e4513ef4a9a0aea870083950bd046a0d6490f93a22", size = 6703640, upload-time = "2026-10-16T22:17:39.313Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c2/6402ee3ccb3363aeed8fdb3f9fe56703ac5377a539f0b81b53999d7e121f/pillow-13.0.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:c6fd031333dedcad7ce3e03d244093f43504f209e86925ebdb2b868fa4037630", size = 7309231, upload-time = "2026-10-16T22:17:41.021Z" }, + { url = "https://files.pythonhosted.org/packages/fc/96/d6b82e8b8c06ad143b66b12e0b31051e4bf489b4fabca1f390a14fe1ebde/pillow-13.0.0-cp315-cp315t-win32.whl", hash = "sha256:c50c80e3591e5cf9a8dfa6007d4f10732f02e32263850999286e56ccd650cfb2", size = 6517200, upload-time = "2026-10-16T22:17:42.886Z" }, + { url = "https://files.pythonhosted.org/packages/60/d4/0062e6005e9b270b165015aafd343364ac378ec5a685431ea42baad33357/pillow-13.0.0-cp315-cp315t-win_amd64.whl", hash = "sha256:adb3c2124c68e480f4632d06cb7caa3b48a51678475f483b4edb1c6dee29ea43", size = 7287488, upload-time = "2026-10-16T22:17:45.56Z" }, + { url = "https://files.pythonhosted.org/packages/e4/81/b8eb349746be7bce47dd95337c6634e84910af91b59aaa9159c034c614fa/pillow-13.0.0-cp315-cp315t-win_arm64.whl", hash = "sha256:4a25756244bdcce3b50580baadf320fa48297f0eeb8e114ba64139a40d4d0fc8", size = 2698073, upload-time = "2026-10-16T22:17:47.556Z" }, + { url = "https://files.pythonhosted.org/packages/60/da/f6d644e631c5b370c5d0b899f3ccadd2780aab070b29a110527cf4e1fd2c/pillow-13.0.0-pp312-pypy312_pp80-macosx_10_15_x86_64.whl", hash = "sha256:8619685cad8efc4c38c66d3b36aad854523297c43d748b3b6f0cc03c90ba3463", size = 5523188, upload-time = "2026-10-16T22:17:59.334Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b0/2594f202d743a35d4fe80682bfd96f277e5ca7aecb27cf64ef5bfc1d000b/pillow-13.0.0-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:7e91e97a929232cdb828889ee6ad0e48d7f40f4ec38818f4e4a8968b2b1af22e", size = 4806808, upload-time = "2026-10-16T22:18:01.188Z" }, + { url = "https://files.pythonhosted.org/packages/8e/ed/d504165ef79af6fafe25c76726cf30f544cc236002f7ed054f1d51adc4ff/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:93ff9c9c3663ce23aaa5d0b6b6abac55359e2a0c06c7e30f3771829af816be63", size = 5464358, upload-time = "2026-10-16T22:18:02.779Z" }, + { url = "https://files.pythonhosted.org/packages/7b/fe/a10aba5503ca13e9e009b8bd0a1a4ce5584bdce246245fd6f3a83701369c/pillow-13.0.0-pp312-pypy312_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e65dd6e75de67b2362a4fa3e16aa627595f65054dc4ec73d64680c84d592fa61", size = 6043514, upload-time = "2026-10-16T22:18:04.538Z" }, + { url = "https://files.pythonhosted.org/packages/c0/37/66b12dc476041fe523bca29c9d58fbf1ea92a4eaf73acfb9e993948f1191/pillow-13.0.0-pp312-pypy312_pp80-win_amd64.whl", hash = "sha256:567f20f1c75897d7663830da6ea8af719e03d712b1d9ee7f813319f9ece42e5a", size = 7366030, upload-time = "2026-10-16T22:18:06.638Z" }, +] + [[package]] name = "pluggy" version = "1.6.0" @@ -656,6 +1063,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, ] +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + [[package]] name = "pytest" version = "9.2.0" diff --git a/wiki/API-Reference.md b/wiki/API-Reference.md index 210ddff..ea9e871 100644 --- a/wiki/API-Reference.md +++ b/wiki/API-Reference.md @@ -1,17 +1,17 @@ -# API Reference +# API reference -Complete reference for every public function and class in HarmonizePy. +Every public name in `harmonizepy`, with its signature, arguments, return value and errors. Each entry links to the page that explains the behaviour behind it. ```python -from harmonizepy import harmonize, combat, remove_batch_effect, HarmonizeConfig -from harmonizepy import adjust_combat, adjust_limma +from harmonizepy import ( + harmonize, HarmonizeConfig, HarmonizeResult, InputScaleWarning, + combat, remove_batch_effect, adjust_combat, adjust_limma, +) ``` ---- - ## `harmonize()` -The main pipeline entry point. Handles structural missingness, sorts and blocks batches, groups features by affiliation, corrects each group, and reassembles the output. +The full pipeline: validate, form affiliations, correct each group, reassemble ([Pipeline](Pipeline)). ```python harmonize( @@ -26,183 +26,109 @@ harmonize( block=None, unique_removal=True, output_file=None, -) -> pd.DataFrame + return_report=False, +) -> pd.DataFrame | HarmonizeResult ``` -### Parameters - -| Parameter | Type | Default | Description | -| --- | --- | --- | --- | -| `data` | `DataFrame`, `str`, or `Path` | required | Features x samples matrix. If a path, read from that TSV/CSV/Parquet file. Feature names must be in `df.index`, sample names in `df.columns`. | -| `description` | `DataFrame`, `str`, or `Path` | required | Batch description. Must have columns `ID`, `sample`, `batch`. If a path, read from that CSV file. | -| `config` | `HarmonizeConfig` or `None` | `None` | If provided, all algorithm settings come from this object. Individual keyword arguments below are ignored. | -| `algorithm` | `"ComBat"` or `"limma"` | `"ComBat"` | Batch correction algorithm. | -| `combat_mode` | `int` (1-4) | `1` | ComBat variant. Ignored when `algorithm="limma"`. | -| `needed_values` | `int` or `None` | `None` | Minimum non-missing observations per batch for a feature to qualify. `None` auto-selects: 2 for modes 1, 3 and limma; 1 for modes 2, 4. | -| `sort` | `"sparsity"`, `"jaccard"`, `"seriation"`, or `None` | `None` | Batch sorting strategy applied before blocking. | -| `block` | `int >= 2` or `None` | `None` | Group this many consecutive sorted batches into one block. | -| `unique_removal` | `bool` | `True` | Rescue singleton-affiliation features by cropping to the nearest shared pattern. | -| `output_file` | `str`, `Path`, or `None` | `None` | Write the corrected matrix to this path. Format inferred from extension: `.tsv`, `.csv`, `.parquet`, `.pq`. | - -### Returns - -`pd.DataFrame` with the same shape, index, and column order as the input. NaN positions are preserved where data was insufficient for correction. - -### Raises - -`ValueError` on invalid arguments, mismatched sample IDs, or duplicate feature names. - -### Examples +| Argument | Type | Default | +| ---------------- | -------------------------------------------------- | ---------- | +| `data` | DataFrame or path | required | +| `description` | DataFrame or path | required | +| `config` | `HarmonizeConfig` or `None` | `None` | +| `algorithm` | `"ComBat"` or `"limma"` | `"ComBat"` | +| `combat_mode` | 1, 2, 3 or 4 | 1 | +| `needed_values` | int >= 1 or `None` | `None` | +| `sort` | `"sparsity"`, `"jaccard"`, `"seriation"` or `None` | `None` | +| `block` | int >= 2 or `None` | `None` | +| `unique_removal` | bool | `True` | +| `output_file` | path or `None` | `None` | +| `return_report` | bool | `False` | + +- `data`, `description`: the two tables of [Input format](Input-Format). A data path is read by its extension; a description path is always read as comma-separated. +- `config`: when given, its fields replace `algorithm`, `combat_mode`, `needed_values`, `sort`, `block` and `unique_removal`, and those keyword arguments are ignored. +- `combat_mode`: see [ComBat](ComBat#the-four-modes). Ignored with limma. +- `needed_values`: values a feature needs in a batch for the batch to count ([Missing values](Missing-Values)). `None` picks 2 for ComBat modes 1 and 3 and for limma, 1 for modes 2 and 4. +- `sort`, `block`: see [Sorting and blocking](Sorting-and-Blocking). `block` must also be below the number of batches. +- `unique_removal`: see [Unique removal](Unique-Removal). +- `output_file`: also write the corrected matrix there: `.csv`, `.parquet` or `.pq` by extension, otherwise tab-separated. +- `return_report`: return the report with the matrix ([Correction report](Correction-Report)). + +Returns the corrected matrix as a DataFrame, with the input's features and columns in the input's order; a feature repeated with the same name and values appears once. Features that could not be corrected keep their measured values or come out empty, as the report records. With `return_report=True`, returns a `HarmonizeResult`. + +Raises `ValueError` on an invalid argument, an input that fails validation, or a feature name repeated with different values; `TypeError` if `unique_removal` is not a bool; `OSError` if a path cannot be read or `output_file` cannot be written; `ImportError` for Parquet without `pyarrow`. Warns with `InputScaleWarning` when the values do not look log-transformed. ```python -from harmonizepy import harmonize - -# From file paths result = harmonize("data.tsv", "batch.csv") - -# From DataFrames -result = harmonize(data_df, desc_df, algorithm="limma") - -# Sort and block for many-batch datasets -result = harmonize(data_df, desc_df, sort="sparsity", block=2) - -# Non-parametric ComBat for small batches -result = harmonize(data_df, desc_df, combat_mode=3, needed_values=1) - -# Write output directly -result = harmonize("data.tsv", "batch.csv", output_file="corrected.parquet") +result = harmonize(data_df, desc_df, algorithm="limma", sort="sparsity", block=2) # needs 3+ batches +result, report = harmonize(data_df, desc_df, return_report=True) ``` ---- +## `HarmonizeResult` -## `HarmonizeConfig` +A named tuple of two DataFrames, returned by `harmonize(..., return_report=True)`; it unpacks as `data, report`. -Frozen dataclass for storing a reproducible run configuration. Pass as `config=` to `harmonize()` to override all individual keyword arguments. +- `data`: the corrected matrix, as `harmonize()` returns it otherwise. +- `report`: one row per feature of `data`, in its order, with the columns `status`, `batches_used`, `group_size`, `cropped` and `repeats_removed` ([Correction report](Correction-Report#columns)). -```python -from harmonizepy import HarmonizeConfig +## `HarmonizeConfig` -cfg = HarmonizeConfig( - algorithm="ComBat", - combat_mode=1, - sort_strategy="sparsity", - block_size=2, - unique_removal=True, -) -``` +A frozen dataclass holding a run's settings, for reuse with `harmonize(data, description, config=cfg)`. -### Fields +| Field | Default | Same as | +| ---------------- | ---------- | ---------------- | +| `algorithm` | `"ComBat"` | `algorithm` | +| `combat_mode` | 1 | `combat_mode` | +| `needed_values` | `None` | `needed_values` | +| `sort_strategy` | `None` | `sort` | +| `block_size` | `None` | `block` | +| `unique_removal` | `True` | `unique_removal` | -| Field | Type | Default | Description | -| --- | --- | --- | --- | -| `algorithm` | `str` | `"ComBat"` | `"ComBat"` or `"limma"` | -| `combat_mode` | `int` | `1` | ComBat mode 1-4 | -| `needed_values` | `int` or `None` | `None` | Minimum observations per batch (auto-selected if `None`) | -| `sort_strategy` | `str` or `None` | `None` | `"sparsity"`, `"jaccard"`, `"seriation"`, or `None` | -| `block_size` | `int` or `None` | `None` | Block size >= 2, or `None` | -| `unique_removal` | `bool` | `True` | Rescue singleton features | +The fields are checked when the instance is created, raising `ValueError` or `TypeError` as `harmonize()` would, and cannot be changed afterwards; make a new instance for other settings. The settings themselves are explained on the pages linked from `harmonize()` above. -`HarmonizeConfig` is frozen and slots-based. Once created, fields cannot be changed. Create a new instance to use different settings. +## `InputScaleWarning` ---- +A `UserWarning` subclass raised by `harmonize()` and the command line when the values look untransformed ([Input format](Input-Format#scale)). Filter it by category to silence it. ## `combat()` -Low-level ComBat engine. Operates directly on NumPy arrays. Does not handle structural missingness: for that, use `harmonize()`. +The ComBat engine on one matrix, with no pipeline around it ([ComBat](ComBat)). ```python -combat( - data, - batch, - *, - par_prior=True, - mean_only=False, - ref_batch=None, -) -> ndarray +combat(data, batch, *, par_prior=True, mean_only=False, ref_batch=None) -> ndarray ``` -### Parameters - -| Parameter | Type | Default | Description | -| --- | --- | --- | --- | -| `data` | `ndarray`, shape `(n_features, n_samples)` | required | Expression matrix. Per-cell NaN is allowed. | -| `batch` | array-like, shape `(n_samples,)` | required | Integer batch label per sample. | -| `par_prior` | `bool` | `True` | Use parametric prior (True = modes 1/2, False = modes 3/4). | -| `mean_only` | `bool` | `False` | Correct location only, skip scale adjustment (True = modes 2/4). | -| `ref_batch` | `int` or `None` | `None` | Reference batch to leave unadjusted. Other batches are adjusted toward this reference. | - -### Returns +- `data`: a features by samples float array; missing cells allowed. +- `batch`: one whole-number label per sample. +- `par_prior`: parametric prior (modes 1 and 2) or non-parametric (modes 3 and 4). +- `mean_only`: correct the location only (modes 2 and 4). +- `ref_batch`: a batch label to leave unchanged and adjust the others toward; it needs at least two samples. -`ndarray` with the same shape as `data`. NaN positions preserved. - -### Example - -```python -import numpy as np -from harmonizepy import combat - -data = np.random.randn(1000, 30) # 1000 features, 30 samples -batch = np.array([1]*10 + [2]*10 + [3]*10) - -corrected = combat(data, batch) -corrected_np = combat(data, batch, par_prior=False) # non-parametric -corrected_loc = combat(data, batch, mean_only=True) # location only -``` - ---- +Returns a new array of the same shape; missing cells stay missing. Features ComBat cannot fit keep their input values ([ComBat](ComBat#features-combat-leaves-raw)). A feature with no value in a batch is fitted on the batches it has. Raises `ValueError` on a wrong shape, a batch length that does not match, labels that are not whole numbers, infinite values, values of magnitude 1e150 or more (whose squares overflow the variance sums), or an invalid `ref_batch`. ## `remove_batch_effect()` -Low-level limma engine. Operates directly on NumPy arrays. Does not handle structural missingness: for that, use `harmonize()`. +The limma engine on one matrix ([limma](limma)). ```python remove_batch_effect(data, batch) -> ndarray ``` -`data` is an ndarray of shape `(n_features, n_samples)`. Per-cell NaN is allowed. `batch` is a 1-D array-like of integer batch labels, length `n_samples`. - -### Returns - -`ndarray` with the same shape as `data`. NaN positions preserved. - -### Example - -```python -import numpy as np -from harmonizepy import remove_batch_effect - -corrected = remove_batch_effect(data, batch) -``` - ---- +Takes the same `data` and `batch` as `combat()`. Returns a new array of the same shape; missing cells stay missing. A feature is fitted on the batches it has values in; one with values in a single batch, or missing a batch with no more values than observed batches, keeps its input values. Called directly, it corrects a single feature; inside `harmonize()` a group of one feature is left raw. Raises `ValueError` as `combat()` does, apart from `ref_batch` and the 1e150 limit. -## `adjust_combat()` +## `adjust_combat()` and `adjust_limma()` -Wrapper that maps HarmonizR-style integer modes (1-4) to the `combat()` parameters. Operates on DataFrames rather than raw ndarrays. +DataFrame wrappers around the engines, for custom pipelines that manage their own groups. ```python adjust_combat(sub_df, batch_labels, mode=1, ref_batch=None) -> pd.DataFrame -``` - -`sub_df` is a features x samples DataFrame. Returns a corrected DataFrame with the same shape, index, and columns. Intended for custom pipeline use when you are managing sub-matrices yourself. - ---- - -## `adjust_limma()` - -Wrapper applying limma correction to a DataFrame. - -```python adjust_limma(sub_df, batch_labels) -> pd.DataFrame ``` -`sub_df` is a features x samples DataFrame. Returns a corrected DataFrame with the same shape, index, and columns. - ---- +`mode` is a ComBat mode, 1 to 4. Both return a corrected DataFrame with the index and columns of `sub_df`, and raise `ValueError` on labels that do not match the columns or are not whole numbers, or on input the engine refuses. -## Semi-public submodule API +## Pipeline helpers -These functions are importable from their submodules for building custom pipelines. They are not re-exported from the top-level `harmonizepy` namespace. +Importable from their modules for custom pipelines; not exported from `harmonizepy` itself. ```python from harmonizepy.sorting import sort_batches @@ -210,10 +136,6 @@ from harmonizepy.blocking import build_block_list from harmonizepy.affiliation import remove_unique_combinations ``` -| Function | Module | Description | -| --- | --- | --- | -| `sort_batches(data, batch_labels, strategy)` | `harmonizepy.sorting` | Returns a reordered copy of `batch_labels` according to the chosen strategy. | -| `build_block_list(batch_labels, block_size)` | `harmonizepy.blocking` | Returns a list of batch-group assignments for the given block size. | -| `remove_unique_combinations(affiliation_list)` | `harmonizepy.affiliation` | Rescues singleton-affiliation features by cropping to the nearest shared pattern. | - -These interfaces are stable for the current version but are not covered by the same backward-compatibility guarantee as the top-level public API. +- `sort_batches(data, batch_list, strategy, needed_values)` returns `(sorted_data, sorted_batch_list, col_order)`: the matrix with its columns reordered so that similar batches are adjacent, the labels in the new order, and the input column index at each new position (`np.argsort(col_order)` restores the input order). +- `build_block_list(batch_list, block_size)` returns the block label of each sample, starting at 1, with every `block_size` batches in order of first appearance sharing a block. +- `remove_unique_combinations(affiliation_list, batches_per_block=None)` takes one affiliation (a tuple of batch or block labels) per feature and returns a new list in which each affiliation held by one feature only is replaced by the longest affiliation of another feature inside it, where one of two or more batches exists; `batches_per_block` maps each block to its number of batches, and `None` counts each block as one batch ([Unique removal](Unique-Removal#the-rule)). diff --git a/wiki/Algorithms.md b/wiki/Algorithms.md index e1bc77c..31a2dd5 100644 --- a/wiki/Algorithms.md +++ b/wiki/Algorithms.md @@ -1,83 +1,65 @@ -# Algorithms +# Choosing an engine -HarmonizePy provides two batch-correction algorithms: **ComBat** and **limma**. Both are implemented in pure NumPy and handle per-cell missing values without imputation. +Which engine fits depends on two questions about the data, should a protein's batch effect be estimated partly from the other proteins, and does a batch change the spread of a protein or only its level, and on one about assumptions: may the batch effects across proteins be taken to follow a known distribution? ComBat and limma answer them differently, and ComBat's four modes cover the combinations. ---- +```mermaid +flowchart LR + Q1[borrow across
proteins?] -- no --> L([limma]):::ok + Q1 == yes ==> Q2[correct
spread too?] + Q2 == yes ==> Q3[normal and
inverse-gamma
priors?] + Q2 -- no --> Q4[normal
prior?] + Q3 == yes ==> M1(["mode 1 (default)"]):::ok + Q3 -- no --> M3([mode 3]):::ok + Q4 -- yes --> M2([mode 2]):::ok + Q4 -- no --> M4([mode 4]):::ok + classDef ok fill:#116329,stroke:#4ac26b,color:#ffffff + linkStyle default stroke:#8b949e +``` -## ComBat +

Figure 1. Three questions, asked in order, pick an engine; modes are ComBat modes, and the thick line leads to the default. Borrowing means estimating each protein's batch effect partly from the other proteins. The last question asks whether the batch shifts may be taken as normal, and the batch spreads as inverse-gamma; a no gives the non-parametric modes. The sections below say what each answer trades away.

-ComBat (Johnson, Li & Rabinovic 2007) is an empirical Bayes method. It models each feature as having a batch-specific location shift and scale change, then uses information shared across all features to estimate and remove those effects. The shared-information step makes ComBat robust even when individual batches are small. +| Engine | Borrows across features | Corrects scale | Prior | +| ----------------------- | ----------------------- | -------------- | -------------- | +| ComBat mode 1 (default) | yes | yes | parametric | +| ComBat mode 2 | yes | no | parametric | +| ComBat mode 3 | yes | yes | non-parametric | +| ComBat mode 4 | yes | no | non-parametric | +| limma | no | no | none | -### The four modes +## Borrowing or not -| Mode | `par_prior` | `mean_only` | What it corrects | Use case | -| --- | --- | --- | --- | --- | -| 1 | `True` | `False` | Location and scale | Default. Most datasets. | -| 2 | `True` | `True` | Location only | Pre-scaled or variance-normalized data | -| 3 | `False` | `False` | Location and scale | Small batches (< ~10 samples), non-Gaussian data | -| 4 | `False` | `True` | Location only | Small batches, pre-scaled data | +ComBat estimates each protein's batch effects partly from the other proteins in its group (see [ComBat](ComBat)). With small batches this steadies estimates that would otherwise follow the noise of a few samples ([Johnson et al. 2007](References#johnson-et-al-2007)). It also means the result for one protein depends on which others share its group, and a group needs at least two features. -**Mode 1** (parametric, location + scale) is the default and appropriate for most bulk proteomics, metabolomics, and microarray datasets where batch sizes are reasonable (10+ samples per batch). +limma fits each protein alone (see [limma](limma)). A protein's correction depends only on its own values, and the batch means of every corrected protein end exactly equal. With few samples per batch, those means carry more noise into the correction. -**Mode 2** (parametric, location only) skips variance correction. Use it when the data has already been variance-normalized or when you want to preserve the measured spread between batches. +## Level only, or level and spread -**Mode 3** (non-parametric, location + scale) makes no distributional assumption about batch effects. It is slower than mode 1 but more appropriate when batch sizes are small, when the data deviates strongly from normality, or when modes 1 and 2 produce overcorrection artifacts. +Modes 1 and 3 also correct each batch's spread; modes 2 and 4, and limma, leave it as it was. Location-only correction is the choice when the differences in spread between batches are to be kept, for example because they were already made comparable before correction. Location-only modes need one value per batch instead of two (`needed_values` 1), so a feature with a single value in a batch can count there. It can still be left raw, for example when it has no spread within batches. -**Mode 4** (non-parametric, location only) combines the robustness of mode 3 with the location-only correction of mode 2. +## Parametric or non-parametric -### Parametric vs non-parametric +The parametric prior assumes the batch effects across proteins follow a normal and an inverse-gamma distribution. The non-parametric prior makes no such assumption and weights the other proteins' estimates directly. It costs more: its work grows with the square of the number of features in a group, where the parametric prior grows in proportion. No measurement here shows one correcting better than the other on real data. -The parametric modes (1, 2) fit a gamma-inverse-gamma hyperprior to the batch effect distribution across features and use it to shrink per-feature estimates. This makes them data-efficient but sensitive to violations of the assumed distribution. +## Checking a choice -The non-parametric modes (3, 4) estimate the prior empirically by integrating over the actual observed distribution. They are more flexible but require more samples to stabilize the estimates and are notably slower on large datasets. +No measurement here ranks the engines or modes in general, and the tests compare against R, not against a known truth (see [Limits](Limits)). Some checks on a given matrix: -### The `needed_values` parameter +- The [correction report](Correction-Report): how many features each setting corrects, leaves raw or empties. +- Batch grouping before and after, for example in a PCA of the corrected features. A batch grouping that has reversed, rather than disappeared, points to over-correction; comparing with limma, which does not borrow, or with mode 2, which leaves the spread alone, can show whether the scale correction or the shrinkage is the cause. +- A known biological difference that is balanced across batches should survive correction. -`needed_values` controls how many non-missing observations a feature must have in a given batch to be included in adjustment for that batch. +## Setting it -The default (`None`) auto-selects: +```python +harmonize(data, batch) # ComBat mode 1 +harmonize(data, batch, combat_mode=3) # ComBat mode 3 +harmonize(data, batch, algorithm="limma") # limma +``` -- `2` for modes 1, 3 and limma (need variance estimate: at least 2 observations) -- `1` for modes 2, 4 (location only: 1 observation suffices) +On the command line: `--combat-mode 3`, `--algorithm limma`. With limma, `combat_mode` must still be a valid mode (1 to 4) but has no effect. -Increase `needed_values` (e.g. to `3`) if you want stricter inclusion and have enough data to afford it. +## Related pages ---- - -## limma - -limma batch correction (`removeBatchEffect`, Ritchie et al. 2015) uses a linear model. It fits batch as a covariate, estimates batch coefficients by ordinary least squares with a sum-to-zero constraint, and subtracts those coefficients from the data. - -limma is: - -- Faster than ComBat (closed-form solution, no iterative EB solver) -- Less aggressive: it corrects location only (no scale correction) -- Fully closed-form: results are determined directly from the data, not from an iterative solver - -Use limma when: - -- Speed is important and the dataset is large -- A single-feature correction is needed (ComBat's EB prior requires multiple features) -- The data has already been variance-stabilized -- You want a lightweight check before running full ComBat - ---- - -## ComBat vs limma: choosing - -Start with ComBat mode 1. It is the most common choice in the literature and covers most bulk proteomics and microarray workflows. - -Switch to limma when you need speed on a large matrix or when mode 1 produces overcorrection (visible as reversed batch grouping in PCA after correction). - -Switch to ComBat mode 3 when: - -- Batch sizes are fewer than ~10 samples -- QC plots show strongly non-Gaussian batch effects after mode 1 - ---- - -## NaN handling in both algorithms - -Both ComBat and limma handle per-cell missing values (stochastic NaN within qualifying batches) using a per-feature approach. For each feature, the computation uses only the observed values in that feature's valid samples. NaN positions in the input remain NaN in the output. - -This matches the behavior of R `sva::ComBat` v3.60.0 (the `Beta.NA` approach). See [[R-Compatibility]] for verification details and [[Pipeline]] for how structural missingness is handled before the engines run. +- [ComBat](ComBat): the model, the priors and the features set aside. +- [limma](limma): the linear model and its edges. +- [Pipeline](Pipeline): both engines run once per affiliation group. diff --git a/wiki/Batch-Effects.md b/wiki/Batch-Effects.md new file mode 100644 index 0000000..df19e57 --- /dev/null +++ b/wiki/Batch-Effects.md @@ -0,0 +1,79 @@ +# Batch effects + +Samples measured on different days, plexes, columns, instruments or sites pick up differences that have nothing to do with their biology. When those differences move many features the same way for every sample processed together, they are a batch effect, and they can be larger than the biology a study is looking for ([Leek et al. 2010](References#leek-et-al-2010)). + +## What a batch is to HarmonizePy + +To HarmonizePy a batch is a whole-number label on each sample, read from the `batch` column of the batch description (see [Input format](Input-Format)). Samples with the same label are assumed to share one technical condition. Nothing else about a sample, such as its condition, subject or tissue, is read. + +In proteomics a batch is usually an LC-MS acquisition series, a TMT plex, an instrument, a column or a processing day ([Cuklina et al. 2021](References#cuklina-et-al-2021)). The tool cannot tell whether one label merges two technical sources or two labels split one, so the batch labels are a design decision made before the run, and the correction is only as good as they are. + +## What the effect looks like in a matrix + +Take one protein measured in two batches of three samples, on a log2 scale: + +```text + s1 s2 s3 | s4 s5 s6 +P2 18.20 18.90 17.70 | 19.80 20.40 19.10 +batch 1 1 1 | 2 2 2 +mean 18.27 | 19.77 +``` + +Batch 2 reads about 1.5 units higher. On a log2 scale that is a 2.8-fold difference in intensity, applied to every sample of the batch. A batch can also change the spread of a feature: one run might be noisier than another. The engines model these, per feature and per batch: + +- a location effect, a shift added to every value of the feature in that batch; +- a scale effect, a factor on the feature's spread in that batch. + +

+ + + + Two panels of simulated values for one protein in two batches. Left: batch 2 is shifted up with the same spread. Right: both batches have the same mean, and batch 2 is spread wider. + +

+

Figure 1. The two kinds of batch effect the engines model. A location effect moves a whole batch; a scale effect leaves the batch mean in place and widens or narrows its spread. Simulated values.

+ +ComBat in modes 1 and 3 removes both. ComBat in modes 2 and 4, and limma, remove the location effect only (see [Choosing an engine](Algorithms)). + +## What correction does to it + +Here are four proteins from the [Quick start](Quick-Start) example, before and after `harmonize()` with the default ComBat mode 1: + +

+ + + + Dot plot of proteins P1 to P4, each sample coloured by batch, with batch means as bars: a gap of about 1.5 between batches before correction, and close means after. + +

+

Figure 2. Each dot is a sample and each bar a batch mean. Before correction every protein's batch 2 mean sits about 1.5 above its batch 1 mean; after it, the two means are within 0.3 of each other, and P3 is still near 23 while P2 is near 19.

+ +The batch means, in numbers: + +```text +before after + batch 1 batch 2 batch 1 batch 2 +P1 19.85 21.33 P1 20.45 20.72 +P2 18.27 19.77 P2 19.08 18.95 +P3 22.40 23.83 P3 23.21 23.02 +P4 19.07 20.63 P4 19.90 19.80 +``` + +The gap of about 1.5 between the batches shrinks to between 0.1 and 0.3, and each protein keeps its own level: P3 stays near 23 and P2 near 19. ComBat does not make the batch means exactly equal. It estimates each protein's batch shift partly from the other proteins in its group, and that shrinkage leaves a small remainder (see [ComBat](ComBat)). + +## Why the log scale matters + +Both engines treat the location effect as something added. On raw intensities a batch effect is closer to a factor (the same run that reads 1000 as 1500 reads 100 as 150), and the spread of a feature grows with its level, so one additive shift and one spread per feature fit poorly ([Rocke and Durbin 2001](References#rocke-and-durbin-2001)). The log turns the factor into a shift. HarmonizePy does not transform the data itself, and warns when the values look untransformed (see [Input format](Input-Format#scale)). + +## When the batch is also the biology + +The batch estimate for a feature is computed from all samples in the batch. If one batch holds mostly treated samples and another mostly controls, the batch estimate mixes the treatment difference with the technical shift, so correction removes part of the treatment effect and leaves part of the technical shift. + +> [!WARNING] +> HarmonizePy reads nothing about a sample beyond its name and batch label. It cannot be told which samples belong to which condition, so it cannot protect a condition that is unevenly spread over batches (see [Limits](Limits)). A design where every batch holds samples of every condition avoids the problem. A corrected matrix that looks clean in a PCA can still have lost the effect the study was designed to find, and batch correction on such a design can overstate the confidence of later tests ([Nygaard et al. 2016](References#nygaard-et-al-2016)). + +## Related pages + +- [Missing values](Missing-Values): why a protein can be absent from a whole batch, and what that does to correction. +- [ComBat](ComBat): how the location and scale effects are estimated and shrunk. +- [limma](limma): the location-only alternative with no sharing between features. diff --git a/wiki/Benchmarks.md b/wiki/Benchmarks.md index 11e0534..80ff84b 100644 --- a/wiki/Benchmarks.md +++ b/wiki/Benchmarks.md @@ -1,118 +1,127 @@ # Benchmarks -This page summarizes benchmark design, dataset catalog, runtime expectations, and how to reproduce results locally. - ---- - -## Design philosophy - -The benchmark suite answers four separate questions: - -- Does HarmonizePy stay numerically aligned with HarmonizR on small and medium synthetic bulk workloads? -- Does that parity hold on real matrices such as DIA proteomics and murine medulloblastoma data? -- Is there at least one R-backed SCP anchor, so the single-cell regime is covered? -- How does the Python implementation behave on stress-scale inputs where HarmonizR baselines are not practical? - -The suite is deliberately split into two passes rather than one combined run. - ---- - -## Dataset catalog - -| Dataset | Shape | Batches | Missingness | Type | Benchmark pass | -| --- | --- | --- | --- | --- | --- | -| `small` | 1000 x 20 | 5 | 30% per-batch | Synthetic bulk | R-backed parity | -| `medium` | 5000 x 60 | 10 | 20% per-batch | Synthetic bulk | R-backed parity | -| `dia` | 8470 x 36 | 2 | Structural | Real DIA proteomics | R-backed parity | -| `murine` | 4753 x 25 | 4 | None injected | Real murine medulloblastoma | R-backed parity | -| `scp_small` | 3000 x 1000 | 20 | 50% abundance-pattern | Synthetic SCP | R-backed parity | -| `large` | 10000 x 100 | 20 | 5% per-batch | Synthetic bulk stress | Python-only | -| `scp_large` | 5000 x 10000 | 100 | 60% abundance-pattern | Synthetic SCP stress | Python-only | - -**R-backed parity datasets** are benchmarked against single-core HarmonizR baselines. Concordance and runtime ratios are both reported. - -**Python-only datasets** are too large for reliable HarmonizR baselines. They are showcased as operational stress runs, not parity evidence. - ---- - -## Runtime headline - -All results are from a single machine: AMD Ryzen 9 3950X (16 physical cores), 125 GiB RAM, Python 3.12.13 with NumPy 2.4.4 linked against scipy-openblas 0.3.31. - -| Dataset | Representative scenario | Python | R (1 core) | Runtime ratio (R/Python) | -| --- | --- | --- | --- | --- | -| `small` | limma | 0.015 s | 1.007 s | ~67x | -| `medium` | ComBat m2, block=2 | 0.070 s | 5.361 s | ~77x | -| `dia` | ComBat m3 | 1.714 s | 456 s | ~266x | -| `murine` | ComBat m4, block=2 | 0.366 s | 28.2 s | ~77x | -| `scp_small` | ComBat m1 | 1.018 s | 54.9 s | ~54x | - -On every benchmarked scenario in this suite, Python runtime was shorter than single-core HarmonizR. The largest runtime differences appear on non-parametric ComBat (modes 3 and 4) and on SCP-scale data. - ---- - -## Concordance summary - -| Scenario | Max relative difference | Status | -| --- | --- | --- | -| `small` ComBat m1 | 5.98e-06 | Near-exact | -| `dia` ComBat m3 | 5.12e-14 | Effectively exact | -| `scp_small` ComBat m1 | 7.04e-06 | Near-exact | -| `medium` ComBat m1, block=2 | 7.39e-06 | Near-exact | -| `medium` ComBat m3 (unblocked) | 2.67e+01 | **Known outlier** | - -The unblocked medium ComBat m3 scenario is the clearest parity caveat in the current suite. The blocked medium pipeline (`block=2`) is in good shape. - ---- - -## Why R is limited to one core - -HarmonizR supports parallelism via `doParallel` and `foreach`. The current benchmark pins it to 1 core because `doParallel` with Unix forked workers and OpenBLAS compete for threads when worker count is increased. This produces worse wall-clock performance and higher memory, not a speedup. The 1-core baseline is the fair and stable reference point for this machine. - ---- - -## How to reproduce - -Run the R-backed parity pass and the Python-only extreme pass separately: +The benchmark suite measures how long `harmonize()` takes and how much memory it uses, and compares its output with single-core HarmonizR on matrices too large for the test fixtures. The latest results are in [`benchmarks/RESULTS.md`](https://github.com/LangeLab/HarmonizePy/blob/main/benchmarks/RESULTS.md) in the repository, measured at a stated version; this page describes what the suite runs and how to read and reproduce it. + +

+ + + + Wall time of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy takes 21 ms to 2.0 s, HarmonizR 1.0 s to 312 s. + +

+

Figure 1. Wall time of one correction on each matrix with an R baseline, both tools on one core. HarmonizR's time includes reading its input file, at most 5% of it here. RESULTS.md has every scenario.

+ +

+ + + + Peak memory of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy 116 to 208 MB, HarmonizR 170 to 848 MB. + +

+

Figure 2. Peak memory of a fresh process that reads both input files, corrects once and exits. Dotted lines mark each tool started and left idle; loading sva adds about 370 MB to HarmonizR's ComBat runs. RESULTS.md has the table.

+ +## Datasets + +| Dataset | Kind | Features | Samples | Batches | R baseline | +| ----------- | --------------------- | -------- | ------- | ------- | ---------- | +| `small` | synthetic bulk | 1000 | 20 | 5 | yes | +| `medium` | synthetic bulk | 5000 | 60 | 10 | yes | +| `large` | synthetic bulk | 10000 | 100 | 20 | no | +| `murine` | real proteomics | 4753 | 25 | 4 | yes | +| `dia` | real DIA proteomics | 8470 | 36 | 2 | yes | +| `scp_small` | synthetic single-cell | 3000 | 1000 | 20 | yes | +| `scp_large` | synthetic single-cell | 5000 | 10000 | 100 | no | + +- The synthetic sets are generated by `benchmarks/datasets.py`: values from a normal distribution, one shift per batch shared by every feature, and missing values removed per feature and batch for the bulk sets, or by a random detection profile for the single-cell sets. They exercise the code at a given shape; they carry no biology and no scale effect, so they say nothing about how well a correction recovers either. +- `large` and `scp_large` run without R: they show how the Python implementation scales. +- `dia` has two batches, so it runs without blocking only. +- The two real matrices are not part of the repository; the suite reads them from `benchmarks/data/` when present. + +## What is measured + +- Wall time of one `harmonize()` call, median over repetitions, after a warm-up run in the R-backed pass. +- Memory within a run: the peak of Python allocations traced by `tracemalloc` during the call, plus the size of the result matrix. +- Memory against HarmonizR: the peak resident set of a fresh process per run (`ru_maxrss`), which reads the two input files, corrects once and exits. It counts everything the operating system gives the tool, interpreter and libraries included; a run that only loads each tool gives its idle cost. HarmonizR runs with BiocParallel set to serial, so all of its work stays in the measured process. +- Against HarmonizR: the largest relative difference, `|py - r| / |r|`, over cells both outputs have, and whether the missing cells sit in the same places. + +HarmonizePy runs on one thread, with BLAS limited to one thread. HarmonizR runs with one R worker. R baselines are cached; `RESULTS.md` records them cached immediately before the Python passes, so both saw the same load. Absolute times on a shared machine still move from day to day; ratios measured in one batch compare. The Python heap and R's `gc()` heap measure different things and do not compare directly; the fresh-process peaks do. + +## Scaling + +A separate sweep corrects synthetic matrices with ten batches, each feature absent from 20% of them, growing either the features or the samples. + +

+ + + + Wall time of limma and the four ComBat modes as features grow from 1,000 to 50,000 at 60 samples, and as samples grow from 40 to 6,000 at 5,000 features. + +

+

Figure 3. Time follows the number of missingness groups, printed along the bottom, which grows far slower than the matrix. The non-parametric modes compare each feature with every other in its group, so they rise once groups get large.

+ +

+ + + + Peak traced memory of one harmonize call against the size of the input matrix, from 0.5 MB to 229 MB, between 2.4 and 3.9 times the input. + +

+

Figure 4. Traced peak of one call against the input matrix as float64: 2.4 to 3.9 times the input over the whole sweep.

+ +

+ + + + Wall time against the share of observed values kept, for limma, ComBat 1 and ComBat 3 at 5,000 and 20,000 features, without blocking and with block=2. + +

+

Figure 5. block=2 joins neighbouring batches, so far fewer groups form and runs take a fraction of the time; a feature missing from one batch of a block loses the whole block, so about 80% of the observed values reach the output. See Sorting and blocking.

+ +## Reading the concordance + +

+ + + + For each matrix with an R baseline, the share of input features each tool corrects, returns as measured, returns empty, or leaves out, with ComBat mode 1. + +

+

Figure 6. What each tool's output holds for every input feature, ComBat mode 1. Both correct the same features; HarmonizePy keeps a row for each feature it cannot correct, and its correction report says why.

+ +Most scenarios agree to within the ComBat convergence threshold or to rounding (see [R compatibility](R-Compatibility#tolerances)). Where missing cells or values differ, the cause is one of these: + +- HarmonizR drops single-feature groups that HarmonizePy keeps with their measured values. +- Without blocking, the two unique-removal rules form different groups for some features (see [Unique removal](Unique-Removal#difference-from-harmonizr)). +- With blocking, the sort strategies can order batches differently. +- HarmonizR returns some features entirely missing in some non-parametric and location-only ComBat runs, although the input has values for them; HarmonizePy corrects them. + +`RESULTS.md` names the cause for each scenario group that does not match. + +## Reproducing + +The R baselines and the memory comparison need R with the packages pinned by `renv.lock` (`sva`, `limma`, `HarmonizR`, `seriation` and their helpers); the other runs need no R. Each run writes a fixed file under `benchmarks/results/`, which is not tracked, and the last command draws every figure on this page from those files. ```bash -# R-backed parity pass (requires a working R + HarmonizR environment) +export OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 +uv run python -m benchmarks.bench cache-r --datasets small medium dia murine scp_small --cores 1 uv run python -m benchmarks.bench run \ --datasets small medium dia murine scp_small \ - --with-r --with-r-cores 1 \ - --n-reps 3 \ + --with-r --with-r-cores 1 --n-reps 3 \ --out benchmarks/results/benchmark_r_parity.json \ --md benchmarks/results/benchmark_r_parity.md - -# Python-only extreme pass uv run python -m benchmarks.bench run \ - --datasets large scp_large \ - --n-reps 1 \ - --no-warmup \ + --datasets large scp_large --n-reps 1 --no-warmup \ --out benchmarks/results/benchmark_python_extremes.json \ --md benchmarks/results/benchmark_python_extremes.md +uv run python -m benchmarks.memory_peak +uv run python -m benchmarks.scaling +uv run python -m benchmarks.outcomes +uv run --group figures python -m benchmarks.figures ``` -The R-backed pass requires R with `sva`, `limma`, `HarmonizR`, and `seriation` installed (managed via `renv` in the repository). The Python-only pass has no R requirement. - -R baseline caches are stored under `benchmarks/results/r_cache/`. If you have already generated them, pass `--use-r-cache` to skip regenerating. - ---- - -## Benchmark CLI +The figures land in `benchmarks/figures/` and, under the names this page uses, in the wiki's `assets/` folder. The suite has its own subcommands: `run`, `cache-r`, `validity`, `profile`, `report` and `generate-data`; `python -m benchmarks.bench --help` lists their options. -The benchmark system has its own CLI with six subcommands: - -- `run`: run Python (and optionally R) benchmarks and produce JSON/Markdown reports -- `cache-r`: pre-generate and cache R baseline outputs for the given datasets -- `validity`: run concordance checks between Python and cached R outputs -- `profile`: profile a specific scenario in-process -- `report`: regenerate Markdown/JSON reports from existing JSON output -- `generate-data`: generate synthetic benchmark datasets - -```bash -uv run python -m benchmarks.bench --help -uv run python -m benchmarks.bench run --help -``` +## Related pages -Raw JSON and Markdown outputs are written to `benchmarks/results/` and are not tracked in version control. The curated summary in `benchmarks/RESULTS.md` is the authoritative benchmark record for each release. +- [R compatibility](R-Compatibility): the fixture tests and the intended differences. +- [Limits](Limits): what the benchmarks do not measure. diff --git a/wiki/CLI-Reference.md b/wiki/CLI-Reference.md index 84f7cc2..aa2fc75 100644 --- a/wiki/CLI-Reference.md +++ b/wiki/CLI-Reference.md @@ -1,96 +1,59 @@ -# CLI Reference - -HarmonizePy includes a command-line interface that exposes the full `harmonize()` pipeline. - -```bash -harmonizepy data.tsv batch.csv [options] +# CLI reference + +The whole command line on one page: the arguments, every flag, config files, the dry run, logging and exit statuses. `harmonizepy` runs the same pipeline as `harmonize()`; `python -m harmonizepy` is the same command. + +```text +usage: harmonizepy [-h] [-o PATH] [--output-format {tsv,csv,parquet}] + [--algorithm {ComBat,limma}] [--combat-mode {1,2,3,4}] + [--needed-values N] [--sort {sparsity,jaccard,seriation}] + [--block N] [--unique-removal | --no-unique-removal] + [--summary PATH] [--report PATH] [--dry-run] + [--config PATH] [--json] [-v | -q] [--log-file PATH] + [--no-log] [--version] + data description ``` ---- - -## Basic examples - -```bash -# Minimal: ComBat mode 1, default output path -harmonizepy data.tsv batch.csv - -# Explicit output path -harmonizepy data.tsv batch.csv -o corrected.tsv - -# limma, write parquet -harmonizepy data.tsv batch.csv --algorithm limma -o corrected.parquet - -# Sort by sparsity and block into pairs -harmonizepy data.tsv batch.csv --sort sparsity --block 2 -o corrected.tsv - -# Validate inputs and print run plan without computing -harmonizepy data.tsv batch.csv --dry-run - -# Save a reproducible JSON summary alongside the result -harmonizepy data.tsv batch.csv -o corrected.tsv --summary run.json -``` - ---- - -## Positional arguments - -- `data`: features x samples matrix (TSV, CSV, or Parquet). The first column is treated as feature names. -- `description`: batch description CSV with columns `ID`, `sample`, `batch`. +## Arguments ---- +- `data`: the data matrix, read by extension: `.csv` comma-separated, `.parquet` or `.pq` Parquet, otherwise tab-separated ([Input format](Input-Format)). +- `description`: the batch description, always read as comma-separated. -## Output flags +## Flags -- `-o`, `--output PATH` (default: `_corrected.tsv`): output file path. Format is inferred from the extension (`.tsv`, `.csv`, `.parquet`, `.pq`). -- `--output-format {tsv,csv,parquet}` (default: inferred from extension): force a specific output format regardless of file extension. Parquet requires `harmonizepy[io]`. +| Flag | Default | Explained on | +| ----------------------------------------- | --------------------------- | -------------------------------------------- | +| `-o`, `--output PATH` | `_corrected.tsv` | below | +| `--output-format {tsv,csv,parquet}` | from the extension | below | +| `--algorithm {ComBat,limma}` | `ComBat` | [Choosing an engine](Algorithms) | +| `--combat-mode {1,2,3,4}` | 1 | [ComBat](ComBat#the-four-modes) | +| `--needed-values N` | 2; 1 in ComBat modes 2, 4 | [Missing values](Missing-Values) | +| `--sort {sparsity,jaccard,seriation}` | none | [Sorting and blocking](Sorting-and-Blocking) | +| `--block N` | none | [Sorting and blocking](Sorting-and-Blocking) | +| `--unique-removal`, `--no-unique-removal` | on | [Unique removal](Unique-Removal) | +| `--report PATH` | none | [Correction report](Correction-Report) | +| `--summary PATH` | none | below | +| `--json` | off | below | +| `--dry-run` | off | below | +| `--config PATH` | none | below | +| `-v`, `--verbose` | off | below | +| `-q`, `--quiet` | off | below | +| `--log-file PATH` | `.log` | below | +| `--no-log` | off | below | +| `--version` | | prints the version | -When `-o` is omitted, the output is written next to the input data file as `_corrected.tsv`. If `--output-format parquet` is given without `-o`, the default becomes `_corrected.parquet`. +## Output ---- +Without `-o`, the corrected matrix is written next to the data file as `_corrected.tsv`, or `.csv` or `.parquet` with `--output-format`. With `-o`, the format comes from the extension (`.csv`, `.parquet`, `.pq`, otherwise tab-separated) unless `--output-format` names one. Missing values are written as empty cells in TSV and CSV, and as nulls in Parquet. Parquet needs the `io` extra. Each output, the report and the summary included, is written to a temporary file beside it and then renamed, so a write that fails leaves no partial file and keeps any file that was there; the log file is written as the run goes. -## Algorithm flags +`--report PATH` writes the per-feature report, by extension (`.csv`, `.parquet` or `.pq`, otherwise tab-separated); `--output-format` does not apply to it. -| Flag | Default | Description | -| --- | --- | --- | -| `--algorithm {ComBat,limma}` | `ComBat` | Batch correction algorithm. | -| `--combat-mode {1,2,3,4}` | `1` | ComBat variant. Ignored when `--algorithm limma`. | -| `--needed-values N` | auto | Minimum non-missing values per batch to qualify a feature. Auto: 2 for modes 1, 3 and limma; 1 for modes 2, 4. | +`--summary PATH` writes a JSON summary after the run: the version, the input and output paths, the settings with the `needed_values` actually used, and the feature, sample and batch counts. `--json` prints the same object to standard output and lowers the log to warnings. ---- - -## Pipeline flags - -| Flag | Default | Description | -| --- | --- | --- | -| `--sort {sparsity,jaccard,seriation}` | none | Sort batches before blocking so similar batches are grouped together. | -| `--block N` | none | Group N consecutive sorted batches into one sub-matrix block. Must be >= 2 and < total number of batches. | -| `--unique-removal` / `--no-unique-removal` | enabled | Rescue singleton-affiliation features. Disable with `--no-unique-removal` for strict missingness-pattern matching. | - ---- - -## Workflow helpers - -- `--dry-run`: validate inputs, print run plan, exit without computing. Exit code `0` if valid, `1` on error. -- `--summary PATH`: write a JSON run summary to PATH after completion. Contains resolved parameters, input/output dimensions, and version. -- `--json`: print the run summary as JSON to stdout. Suppresses INFO log messages. -- `--config PATH`: load flags from a TOML, JSON, or YAML config file. CLI flags override config file values. - ---- - -## Verbosity flags - -- `-v`, `--verbose`: enable debug logging (sub-matrix dimensions, affiliation counts, timing). -- `-q`, `--quiet`: suppress all progress messages. Only warnings and errors are shown. -- `--log-file PATH`: write a detailed execution log to PATH (default: `.log`). -- `--no-log`: disable file logging entirely. - ---- +No output may overwrite an input or another output: a run whose `-o`, `--summary`, `--report` or log file names the data file, the description, or another of these files stops with a usage error (exit code 2) before anything is read. ## Config files -Pass `--config path/to/config.toml` to load settings from a file. TOML, JSON, and YAML are supported. YAML requires the `harmonizepy[config]` extra. - -### TOML example +`--config PATH` reads settings from a TOML, JSON or YAML file (`.toml`, `.json`, `.yaml`, `.yml`); YAML needs the `config` extra. Its keys are the long flag names with underscores, and each value is checked like the matching flag, so a value the flag would refuse is a usage error: ```toml algorithm = "ComBat" @@ -99,46 +62,39 @@ sort = "sparsity" block = 2 unique_removal = true output = "corrected.tsv" +report = "report.tsv" ``` -### JSON example +- Allowed keys: `algorithm`, `combat_mode`, `needed_values`, `sort`, `block`, `unique_removal`, `output`, `output_format`, `summary`, `report`. Any other key is a usage error. +- Flags on the command line override the file. +- Paths in the file are taken relative to the current directory, not to the file. +- A value from the file passes the same type and choice checks as its flag: `combat_mode: 7` or `output_format: xlsx` is a usage error (exit code 2) naming the key. A value the flag accepts but the library refuses, such as `block = 1`, exits with status 1, as the flag does. -```json -{ - "algorithm": "ComBat", - "combat_mode": 1, - "sort": "sparsity", - "block": 2, - "unique_removal": true -} -``` +## Dry run -Config file keys map 1:1 to CLI flag names: `algorithm`, `combat_mode`, `needed_values`, `sort`, `block`, `unique_removal`, `output`, `output_format`, `summary`. CLI flags override config file values. Config file values override built-in defaults. +`--dry-run` reads and validates the inputs and plans the groups exactly as a run would, sorting, blocking and unique removal included, then prints the plan and exits without correcting or writing anything. It refuses `--log-file`, `--summary`, `--json` and `--report` on the command line, even when the flag repeats the config file's value, and ignores `summary` and `report` in a config file. The input-scale warning still prints. -Config paths are resolved relative to the config file, not the current working directory. +The plan it prints is shown on [Quick start](Quick-Start#2-check-the-plan). ---- +## Logging -## Dry-run output +Progress goes to standard error as `INFO [harmonizepy] ...` lines. `-v` adds debug lines (affiliation counts, per-group detail); `-q` and `--json` show warnings and errors only. The input-scale warning is a Python warning, not a log line, and prints under `-q` too. -`--dry-run` validates inputs and prints a summary without running correction: +A log file with debug detail is written next to the output as `.log`, replacing any earlier one; `--log-file PATH` moves it and `--no-log` turns it off. It is opened before the inputs are read, so a run that fails validating its input still leaves a log; a missing input file stops the run before the log is opened. -```bash -HarmonizePy 0.3.2 dry run -──────────────────────────────────────────────────── -Features: 1500 -Samples: 45 -Batches: 5 -Sub-matrices: 3 (unique affiliation groups) -Algorithm: ComBat mode 1 -Sort strategy: sparsity -Block size: 2 -Unique removal: enabled -Inputs valid. Use without --dry-run to run correction. -``` +## Exit status + +| Status | Meaning | +| ------ | ---------------------------------------------- | +| 0 | success, or a valid dry run | +| 1 | input, validation, correction or output error | +| 2 | usage error, or a missing input or config file | ---- +- Status 1 prints one line starting `ERROR` to standard error, such as `ERROR: ...` for invalid input or `ERROR writing output to ...` when a file cannot be written. +- Status 2 covers what the argument parser refuses (an unknown choice, a value that is not a number, `-v` with `-q`), config file errors (unknown key, unsupported extension, unreadable file, a value the matching flag would refuse), dry-run conflicts, and outputs that would overwrite an input or each other. It prints the usage and a `harmonizepy: error:` line. +- A value the parser accepts but the library refuses, such as `--block 1` or `--needed-values 0`, exits with status 1. +- A summary that cannot be written prints a warning and does not change the status. -## Exit codes +## Shell completion -Exit code `0` on success (or `--dry-run` with valid inputs). Exit code `1` on validation error or unrecoverable runtime error. +With the `completion` extra installed, `harmonizepy` supports tab completion through argcomplete. Activate it as argcomplete's documentation describes for your shell, for example `eval "$(register-python-argcomplete harmonizepy)"` in bash. diff --git a/wiki/ComBat.md b/wiki/ComBat.md new file mode 100644 index 0000000..17461ca --- /dev/null +++ b/wiki/ComBat.md @@ -0,0 +1,141 @@ +# ComBat + +A batch of three samples gives a noisy estimate of how far one protein is shifted in that batch. ComBat ([Johnson et al. 2007](References#johnson-et-al-2007); as implemented in the R package `sva`, [Leek et al. 2012](References#leek-et-al-2012)) steadies those estimates by borrowing from the other proteins in the same group: each protein's batch shift, and in modes 1 and 3 its batch scale, is pulled toward what is typical for that batch across all of them. That borrowing is empirical Bayes, and it is what separates ComBat from fitting each protein on its own, as [limma](limma) does. + +HarmonizePy runs ComBat once per affiliation group (see [Pipeline](Pipeline)). Everything below happens inside one group: its features, and the samples of its batches. + +## The model + +For feature $`g`$ in sample $`j`$ of batch $`i`$: + +```math +y_{gj} = \alpha_g + \sigma_g \left( \gamma_{gi} + \sqrt{\delta_{gi}}\, \varepsilon_{gj} \right), \qquad \varepsilon_{gj} \sim N(0, 1) +``` + +- $`\alpha_g`$ is the feature's overall level, the mean of its batch means weighted by the number of samples in each batch. +- $`\sigma_g`$ is its pooled spread within batches. +- $`\gamma_{gi}`$ is the location effect of batch $`i`$: a shift, in units of $`\sigma_g`$. +- $`\delta_{gi}`$ is the scale effect of batch $`i`$: a factor on the variance. + +Here $`\delta_{gi}`$ is a factor on the variance, as in `sva`; Johnson et al. write the same factor as $`\delta_{gi}^2`$. There are no other terms. The batch label is the only thing the model knows about a sample (see [Batch effects](Batch-Effects#when-the-batch-is-also-the-biology)). + +## How a group is corrected + +```mermaid +flowchart LR + E["standardise;
estimate shift
and spread"] ==> P + subgraph prior [shared by the group] + P["one prior
per batch"] + end + P ==> S["shrink toward
the prior
(mode 1: iterate)"] + S ==> R(["remove shift
and spread"]):::ok + classDef ok fill:#116329,stroke:#4ac26b,color:#ffffff + style prior fill:none,stroke:#8b949e,stroke-dasharray:3 3 + linkStyle default stroke:#8b949e +``` + +

Figure 1. One group's fit. In mode 1 the shrink step repeats until the largest relative change is below 1e-4. The prior is the only place where features meet: each feature's own estimates are pulled toward what the other features of its group show in the same batch. That is why adding or removing a feature can move the others.

+ +1. Standardise. Each value becomes $`s_{gj} = (y_{gj} - \hat\alpha_g)/\hat\sigma_g`$. +2. Estimate per feature and batch. $`\hat\gamma_{gi}`$ is the mean of the feature's standardised values in the batch, and $`\hat\delta_{gi}`$ their variance. +3. Shrink. Each batch gets a prior from all features' estimates in that batch, and each feature's estimates move toward it. How far depends on how much data the feature has in the batch and how much the features disagree. +4. Remove. The shrunk effects $`\gamma^*`$ and $`\delta^*`$ are taken out and the scale and level put back: + +```math +\hat y_{gj} = \hat\sigma_g \, \frac{s_{gj} - \gamma^*_{gi}}{\sqrt{\delta^*_{gi}}} + \hat\alpha_g +``` + +Missing cells are skipped at every step: each feature's estimates use the cells it has, and a missing cell stays missing. + +The pooled spread $`\hat\sigma_g^2`$ follows `sva::ComBat`. In a group with no missing cell it is the mean of the squared residuals from the batch means: their sum over the $`N`$ samples, divided by $`N`$. In a group with any missing cell, every feature uses the sample variance of its residuals instead, their sum divided by the feature's own number of values minus one. A single missing cell therefore changes how every feature of its group is scaled: a complete feature's variance grows by the factor $`N/(N-1)`$. + +## Parametric and non-parametric priors + +Modes 1 and 2 use the parametric prior. In each batch the location effects are given a normal prior, and in mode 1 the scale effects an inverse-gamma prior, with their parameters estimated from the features by the method of moments of Johnson et al. Mode 2 has no scale to estimate, and its shrunk location has a closed form. Mode 1 finds each feature's location and scale by iterating two update formulas until the largest relative change in the batch is below $`10^{-4}`$, the threshold `sva` uses. The relative change is measured against the absolute value of the previous estimate, where `sva` divides by the signed previous location, so a feature whose location estimate is negative does not enter `sva`'s test; the two can stop at different iterations, and on the test fixtures, mode 1 agrees with `sva` within the tests' tolerances (see [R compatibility](R-Compatibility#tolerances)). + +For batch $`i`$ the prior's parameters are the method-of-moments estimates over the $`G`$ features of the group: $`\bar\gamma_i`$ and $`\tau_i^2`$ are the mean and sample variance of the $`\hat\gamma_{gi}`$, and with $`m_i`$ and $`s_i^2`$ the mean and sample variance of the $`\hat\delta_{gi}`$, the inverse-gamma prior has + +```math +a_i = \frac{2 s_i^2 + m_i^2}{s_i^2}, \qquad b_i = \frac{m_i s_i^2 + m_i^3}{s_i^2} +``` + +A feature with $`n`$ values in the batch then moves toward the prior mean by + +```math +\gamma^*_{gi} = \frac{n \tau_i^2 \hat\gamma_{gi} + \delta^*_{gi} \bar\gamma_i}{n \tau_i^2 + \delta^*_{gi}} +``` + +so a feature with few values, or a batch whose features agree closely (small $`\tau_i^2`$), is pulled furthest. Mode 1 alternates this with the matching update of $`\delta^*_{gi}`$; mode 2 fixes $`\delta^* = 1`$ and $`n = 1`$. + +

+ + + + Twelve features' batch 2 shifts: each open ring is the feature's own estimate and each filled dot its value after ComBat mode 2 shrinkage, with arrows toward the batch prior mean. + +

+

Figure 2. Shrinkage on twelve simulated features with two batches of four. Each arrow runs from a feature's own estimate of its batch 2 shift to its value after ComBat mode 2. The furthest estimates move the most, toward the prior mean shared by all twelve; the drawn values reproduce combat() to 1e-9.

+ +Modes 3 and 4 use no distribution for the effects. A feature's estimate in a batch is the average of the other features' estimates, each weighted by how well it explains the feature's observed values under a normal likelihood. The average is computed exactly over the other features in the group; there is no sampling, so the same input always gives the same output. Its cost grows with the square of the number of features in a group. + +## The four modes + +`combat_mode` picks a pair of switches, the same pairs HarmonizR passes to `sva::ComBat`: + +| Mode | Prior | Scale corrected | `par_prior` | `mean_only` | `needed_values` | +| ---- | -------------- | --------------- | ----------- | ----------- | --------------- | +| 1 | parametric | yes | `True` | `False` | 2 | +| 2 | parametric | no | `True` | `True` | 1 | +| 3 | non-parametric | yes | `False` | `False` | 2 | +| 4 | non-parametric | no | `False` | `True` | 1 | + +- Mode 1 is the default. +- Modes 2 and 4 correct the location only, so each batch keeps the spread it had. They need only one value per batch, since no variance is estimated in a batch; the default `needed_values` follows. +- Any batch with a single sample makes ComBat correct the whole group in location-only mode, whatever the mode, because one sample has no spread. The run log says so. Inside `harmonize()` this needs `needed_values=1`: with the default of 2, a one-sample batch never counts for any feature, and its sample comes out empty. + +The modes on protein P2 of the [Quick start](Quick-Start) example (batches 1 and 2; batch 3 is outside its group): + +```text + s1 s2 s3 s4 s5 s6 +input 18.20 18.90 17.70 19.80 20.40 19.10 +mode 1 19.02 19.66 18.57 18.98 19.52 18.35 +mode 2 19.11 19.81 18.61 18.89 19.49 18.19 +mode 3 19.03 19.64 18.60 18.97 19.53 18.32 +mode 4 19.34 20.04 18.84 18.66 19.26 17.96 +``` + +

+ + + + Protein P2's six values, coloured by batch, in the input and after ComBat modes 1 to 4 and limma, with batch means as vertical bars. In the input the batch 2 mean is 1.5 above batch 1; every corrected row closes most of that gap, and the ComBat rows end with batch 1 slightly above batch 2. + +

+

Figure 3. Every engine closes most of the 1.5 gap between P2's batch means; the ComBat modes go slightly past it, leaving batch 1 above batch 2 by 0.13 (mode 1) to 0.78 (mode 4). Modes 2 and 4 move each batch as a whole, so the spacing of the dots inside a batch is exactly the input's; modes 1 and 3 also rescale it, and limma puts the two means at the same value.

+ +All four close most of the gap of about 1.5 between the batches, and end with batch 1 above batch 2 by 0.13, 0.31, 0.15 and 0.78. ComBat does not set each protein's batch means equal: it estimates each protein's batch shift partly from the other proteins in its group, so what remains can fall on either side. Modes 2 and 4 keep the input's differences within each batch exactly (0.7 and 1.2 below the highest sample in batch 1); modes 1 and 3 also rescale them. + +## Features ComBat leaves raw + +Some features cannot be estimated, and fitting them would also move the prior for every other feature. ComBat sets them aside, fits the rest as if they were absent, and returns them with their measured values. Their correction would come from the variance floor, not from their data, and I would rather return a measured value than one made up that way: + +- a feature whose pooled variance is below $`10^{-12}`$, such as one constant within every batch, in every mode; +- in mode 1, a feature whose variance in some batch with two or more values is below $`10^{-12}`$ of its pooled variance, such as one constant within a batch (modes 2 to 4 keep such a feature in the fit and correct it); +- a feature with values in one batch only; +- with `ref_batch`, a feature with no value in the reference batch. + +When fewer than two features remain, there is no prior to form, and the group is returned as given. The [correction report](Correction-Report) names each case that `harmonize()` can meet; the reference-batch case arises only in direct calls. `sva::ComBat` leaves out rows with zero variance in a batch too, with a narrower test; the differences are on [R compatibility](R-Compatibility). + +## A feature missing a whole batch + +Inside a group, every feature has values in every batch, so this case does not arise in `harmonize()`. Called directly, `combat()` fits a feature that has no value in one batch on the batches it has. `sva::ComBat` stops with a singular-matrix error on the same input. + +## Reference batch + +`combat()` and `adjust_combat()` take `ref_batch`: that batch is left unchanged, and the others are adjusted toward it, with the level and pooled spread taken from the reference batch alone. HarmonizePy requires at least two samples in the reference batch; `sva` only checks that the label exists. `harmonize()` does not take `ref_batch`, because a group need not contain any given batch. + +## Related pages + +- [Choosing an engine](Algorithms): ComBat against limma, and mode against mode. +- [Correction report](Correction-Report): the statuses for features set aside. +- [API reference](API-Reference#combat): the `combat()` and `adjust_combat()` signatures. diff --git a/wiki/Correction-Report.md b/wiki/Correction-Report.md new file mode 100644 index 0000000..4dd1e43 --- /dev/null +++ b/wiki/Correction-Report.md @@ -0,0 +1,99 @@ +# Correction report + +After a run, some features were corrected, some kept their measured values, and some came out empty. The correction report says which, one row per feature, with the reason. It is the way to audit a run without reading the log. + +I leave a feature uncorrected rather than correct it where its batch effect cannot be estimated, and that choice is only fair if it is visible. The report is where it is visible. + +## Getting it + +From Python, ask for it with `return_report=True`; `harmonize()` then returns a `HarmonizeResult`, which unpacks into the matrix and the report: + +```python +result, report = harmonize("proteins.tsv", "batches.csv", return_report=True) +report["status"].value_counts() +``` + +From the command line, `--report PATH` writes it to `PATH`. Its format follows the extension: `.csv`, `.parquet` or `.pq`, otherwise tab-separated. For the [Quick start](Quick-Start) example: + +```text +protein status batches_used group_size cropped repeats_removed +P1 corrected 1,2 4 False 0 +P2 corrected 1,2 4 False 0 +P3 corrected 1,2 4 False 0 +P4 corrected 1,2 4 True 0 +P5 raw_alone_in_pattern 1 False 0 +P6 missing_no_usable_batch 0 False 0 +P7 raw_single_batch 1 False 0 +P8 missing_no_usable_batch 0 False 0 +``` + +## Columns + +| Column | Holds | +| ----------------- | ------------------------- | +| `status` | outcome, below | +| `batches_used` | batch labels of the group | +| `group_size` | features in the group | +| `cropped` | moved by unique removal | +| `repeats_removed` | identical repeats dropped | + +- `batches_used` lists the batches the feature was corrected over, sorted and comma-separated, and is empty when it was not corrected. With blocking it lists every batch of the group's blocks. +- `group_size` is 0 for a feature with no usable batch. +- `repeats_removed` counts rows with the same name and the same values that were removed before correction (see [Input format](Input-Format#repeated-features)). + +## Statuses + +| Status | Output values | +| ------------------------- | ------------- | +| `corrected` | corrected | +| `raw_single_batch` | measured | +| `raw_alone_in_pattern` | measured | +| `raw_zero_variance` | measured | +| `raw_too_few_features` | measured | +| `raw_too_few_values` | measured | +| `missing_no_usable_batch` | empty | + +A raw feature keeps its measured values inside its own group's batches. Outside them its cells are empty, as for a corrected feature. + +### `corrected` + +The engine fitted the feature with the rest of its group. + +### `raw_single_batch` + +The feature's group spans one batch, or with blocking one block that holds one batch. There is no other batch to correct it against. P7, measured only in batch 3, is the example. + +### `raw_alone_in_pattern` + +No other feature shares the feature's affiliation, and [unique removal](Unique-Removal) found no other feature's affiliation of two or more batches inside it, or was switched off. A group of one is not corrected: ComBat has no other feature to form a prior from, and limma would remove the feature's own batch differences, real ones included. P5 is the example. + +### `raw_zero_variance` + +ComBat only. The feature's variance is too small to scale by: its pooled variance is below $`10^{-12}`$ in any mode, or in mode 1 its variance in one batch is below $`10^{-12}`$ of its pooled variance. A feature constant within each batch is one example. Fitting it would also distort the prior for every other feature, so ComBat fits the group without it. In ComBat mode 2 the example's P6, with one value in each batch, has zero spread within batches and ends here. + +### `raw_too_few_features` + +ComBat only. After the features above were set aside, fewer than two features were left in the group, and a prior needs two. + +### `raw_too_few_values` + +limma only. The feature has no more values than batches it is observed in, such as one value in each batch, so the fit would leave no residual and collapse it to one number. With limma and `needed_values=1`, the example's P6 ends here (see [limma](limma#edges-worth-knowing)). + +### `missing_no_usable_batch` + +No batch has at least `needed_values` values of the feature (with blocking, no block whose every batch has), so it has no affiliation. Its row is empty in the output, even if it had measured values. P6 (one value in each of three batches) and P8 (empty) are the examples. + +## Reading a run + +> [!TIP] +> `report["status"].value_counts()` is the one-line summary of a run. Compare it between two settings before choosing one. + +- A count of `cropped` rows tells how many features gave up batches to unique removal; switching it off turns them into `raw_alone_in_pattern`. +- Many `missing_no_usable_batch` rows can mean `needed_values` is higher than the data support, or blocks too large for the coverage. +- `raw_single_batch` rows are features whose group spans one batch. A protein measured in one batch only can never be corrected; one with a few values elsewhere may join a larger group with a lower `needed_values`. + +## Related pages + +- [Pipeline](Pipeline): the path from affiliation to status, as a diagram. +- [ComBat](ComBat#features-combat-leaves-raw): the rules behind the ComBat-only statuses. +- [CLI reference](CLI-Reference): `--report` and the other output flags. diff --git a/wiki/Home.md b/wiki/Home.md index cd65a4e..e9a3f56 100644 --- a/wiki/Home.md +++ b/wiki/Home.md @@ -1,57 +1,42 @@ # HarmonizePy -Pure-Python batch-effect harmonization for omics data. Validated against R `sva::ComBat`, `limma::removeBatchEffect`, and `HarmonizR` v1.10.0. +HarmonizePy removes batch effects from omics matrices that have missing values, in Python, without imputing anything and without R at runtime. It runs ComBat or limma's `removeBatchEffect` inside the pipeline of HarmonizR, an R package for the same problem: each feature is corrected together with the features that have enough values in the same set of batches (after one adjustment, unique removal, that moves lone features into a shared set), and only on the values that were actually measured. -**Version:** 0.3.2 | **Status:** Alpha | **License:** GPL-3.0 | **Python:** 3.12 - 3.14 +It is written for proteomics first, where a protein can be missing from a whole batch, and works on any features by samples matrix of log-scale values. ---- +

+ + + + Four proteins measured in two batches: batch 2 reads about 1.5 units higher before correction, and the two batch means come within 0.3 of each other after harmonize(). + +

+

Figure 1. Four proteins from the Quick start example. Each short bar is a batch mean: the dashed line between them is the batch effect, and after correction it is nearly flat while each protein keeps its own level.

-## What it does +## Why it exists -Batch effects are systematic technical differences between samples processed at different times, in different labs, or on different instruments. Left uncorrected, they dominate downstream analyses and obscure real biology. +Here and elsewhere in this wiki, "I" is the author of HarmonizePy. -HarmonizePy corrects batch effects in omics datasets where **structural missingness** is common. In proteomics, metabolomics, and single-cell data, many features are absent from entire batches because they were simply not detected, not because they were measured as zero. Standard ComBat and limma implementations require complete matrices and fail on these inputs. +Labs run their pipelines in Python. Calling R from Python adds a second runtime, a second package manager, and a version pin that the Python user does not control, so I wanted the HarmonizR approach ([Voss et al. 2022](References#voss-et-al-2022)) without any of that. -HarmonizePy solves this by grouping features by their batch-observation pattern, correcting each compatible group independently with ComBat or limma, and reassembling the original matrix. Missing values are never imputed: if a feature is missing, it stays missing. +HarmonizR is the reference I check HarmonizePy against, not a target it copies. Where HarmonizePy behaves differently, the difference is a decision, taken because it improves the statistics or keeps more of the user's data, and it is documented on [R compatibility](R-Compatibility). -## Key features +## At a glance -- **ComBat** (all 4 modes) and **limma** batch-correction engines implemented in pure NumPy -- **HarmonizR-compatible pipeline**: structural missingness handling, batch sorting, blocking, unique-combination rescue -- **No imputation**: NaN in, NaN out. The missing-value structure is preserved exactly -- **No R required at runtime**: runs on any Python environment -- **CLI included**: `harmonizepy data.tsv batch.csv -o corrected.tsv` -- **Validated against R reference outputs** across synthetic and real proteomics datasets +- Two engines: ComBat (empirical Bayes, four modes) and limma `removeBatchEffect`, both in NumPy. +- Missing values stay missing. A feature is corrected only over the batches where it has enough values; the rest of its row comes out empty. +- Every run can report what happened to each feature: corrected, kept with its measured values and why, or emptied. +- Results are compared against committed outputs of `sva::ComBat`, `limma::removeBatchEffect` and HarmonizR 1.10.0, with the tolerance stated for each test. +- One call from Python, `harmonize("data.tsv", "batch.csv")`, or one command, `harmonizepy data.tsv batch.csv`. -## 5-second example +## Where to start -```python -from harmonizepy import harmonize - -result = harmonize("data.tsv", "batch.csv") -``` - -That is the entire API for most use cases. `result` is a `pandas.DataFrame` with the same shape as the input. - ---- - -## Documentation - -- [[Installation]]: install options, optional extras, dependencies -- [[Quick-Start]]: minimal working examples, choosing settings -- [[Input-Format]]: data matrix and batch description format, validation rules -- [[Algorithms]]: ComBat modes 1-4, limma, when to use each -- [[Pipeline]]: structural missingness, sorting, blocking, unique removal, NaN handling -- [[API-Reference]]: full signature for every public function and class -- [[CLI-Reference]]: all command-line flags, config files, output formats -- [[R-Compatibility]]: what matches R, what differs, numerical tolerances -- [[Benchmarks]]: dataset catalog, runtime expectations, how to reproduce - ---- +- New to the tool: [Installation](Installation), then [Quick start](Quick-Start), which runs one small matrix from start to finish. +- New to batch correction: [Batch effects](Batch-Effects) and [Missing values](Missing-Values) explain what the tool removes and what it refuses to invent. +- Deciding settings: [Choosing an engine](Algorithms), then [ComBat](ComBat) or [limma](limma). +- Checking a run: [Correction report](Correction-Report) explains every status a feature can end with. +- Before relying on it: [Limits](Limits) lists what HarmonizePy does not do. ## References -- Johnson WE, Li C, Rabinovic A. "Adjusting batch effects in microarray expression data using empirical Bayes methods." *Biostatistics* 8(1):118-127, 2007. -- Ritchie ME et al. "limma powers differential expression analyses for RNA-sequencing and microarray studies." *Nucleic Acids Research* 43(7):e47, 2015. -- Voß H et al. "HarmonizR enables data harmonization across independent proteomic datasets with appropriate handling of missing values." *Nature Communications* 13:3523, 2022. -- Schlumbohm S, Neumann JE, Neumann P. "HarmonizR: blocking and singular feature data adjustment improve runtime efficiency and data preservation." *BMC Bioinformatics*, 2025. +The methods behind HarmonizePy are ComBat ([Johnson et al. 2007](References#johnson-et-al-2007)), limma ([Ritchie et al. 2015](References#ritchie-et-al-2015)) and the HarmonizR approach ([Voss et al. 2022](References#voss-et-al-2022); [Schlumbohm et al. 2025](References#schlumbohm-et-al-2025)). Every reference used in this wiki is on [References](References). diff --git a/wiki/Input-Format.md b/wiki/Input-Format.md index 5dbebd7..dd55135 100644 --- a/wiki/Input-Format.md +++ b/wiki/Input-Format.md @@ -1,116 +1,108 @@ -# Input Format +# Input format -HarmonizePy requires two input files (or DataFrames): a **data matrix** and a **batch description**. +A run takes two tables: the data matrix, with one row per feature and one column per sample, and the batch description, which gives each sample its batch. Both can be files or pandas DataFrames. ---- +

+ + + + The two input files side by side: the data matrix with a protein column and sample columns, and the batch description with ID, sample and batch columns; an arrow shows that the matrix's column names are the description's IDs. + +

+

Figure 1. The two tables meet on the sample name. Every column of the matrix must appear exactly once in the description's ID column; sample is never read, and batch gives each sample its batch.

-## Data matrix - -The data matrix is a features-by-samples table. Features (proteins, peptides, metabolites, genes) are rows. Samples are columns. - -### File format -- Tab-separated (`.tsv`) or comma-separated (`.csv`) -- The first column contains feature names (used as the DataFrame index) -- All remaining columns are samples, one column per sample -- Values are floating-point numbers -- Missing values are represented as empty cells or `NaN` - -### Example - -```tsv -ProteinID Sample_1 Sample_2 Sample_3 Sample_4 Sample_5 Sample_6 -P00001 12.4 11.8 12.1 13.0 12.7 -P00002 8.3 8.1 8.9 8.4 8.7 8.2 -P00003 7.2 7.1 7.5 -P00004 15.1 14.9 15.3 15.0 14.8 15.2 -``` - -Here `P00001` is missing in Sample_4, and `P00003` is missing in Samples 1, 2, and 5. This is typical structural missingness. HarmonizePy handles this without imputation. - -### Rules - -- Feature names must be unique (duplicate index values raise a `ValueError`) -- All non-index values must be numeric. Non-numeric text cells (other than NaN markers) raise a `ValueError` -- An all-NaN row is allowed and passes through unchanged -- No minimum number of features is enforced, but at least 2 features are needed for ComBat's empirical Bayes prior estimation +## Data matrix -### When passing a DataFrame +Features (proteins, peptides, metabolites, genes) are rows; samples are columns. The first column of a file holds the feature names, and the rest are samples: -```python -# Feature names must be in df.index -# Sample names must be in df.columns -data = pd.read_csv("data.tsv", sep="\t", index_col=0) +```text +protein s1 s2 s3 s4 s5 s6 +P1 20.1 19.6 21.3 20.9 21.8 +P2 18.2 18.9 17.7 19.8 20.4 19.1 ``` -The `index_col=0` is required. Without it, pandas will treat the feature name column as a data column and raise a validation error. +The reader is chosen by the file's extension: ---- +| Extension | Read as | +| ----------------- | ------------------------------ | +| `.csv` | comma-separated | +| `.parquet`, `.pq` | Parquet (needs the `io` extra) | +| any other | tab-separated | -## Batch description +- A Parquet file must hold the feature names as its index. A feature-name column that is not the index is read as a sample and refused as text. +- A DataFrame must have the feature names as its index and the samples as its columns. Read a file with `pd.read_csv("data.tsv", sep="\t", index_col=0)`; without `index_col=0` the name column becomes a text column and the run is refused. +- Missing values are empty cells or pandas' usual markers, among them `NA`, `NaN`, `nan`, `null`, `N/A`, `#N/A`, `None` and ``. A `-` is not a missing marker: it makes its column text, and the run is refused. +- Feature names are read as written, as text: a protein named `NA` keeps that name, and `001` stays `001`. +- Every sample column must be numeric. A text cell anywhere in a column fails the whole column, with `data contains non-numeric columns: [...]`. R's HarmonizR turns such a cell into a missing value without a word; I refuse it, because silent coercion can hide a data preparation error. +- Sample names must be unique, in a file header as in a DataFrame. +- Infinite values are refused, naming the first features that hold them (see [Scale](#scale)). With ComBat, so are values of magnitude 1e150 or more, whose squares overflow its variance sums; log-scale data are far below that. +- A row with no values at all is kept and comes out empty, with the status `missing_no_usable_batch`. -The batch description maps each sample to a batch. It is a CSV file with three required columns. +### Repeated features -### Columns +A feature name can appear more than once only with identical values in every cell, missing cells included. The first row is kept and the others are removed, and the log says so: -| Column | Type | Description | -| --- | --- | --- | -| `ID` | string | Sample name. Must match a column name in the data matrix exactly. | -| `sample` | integer | Sample index. Must be unique per row. Used for ordering. | -| `batch` | integer | Batch label. Samples with the same batch value are corrected together. | - -### Example - -```csv -ID,sample,batch -Sample_1,1,1 -Sample_2,2,1 -Sample_3,3,2 -Sample_4,4,2 -Sample_5,5,3 -Sample_6,6,3 +```text +INFO [harmonizepy] Removed 1 repeated feature(s) with identical values: P2 ``` -In this example, Samples 1 and 2 are in batch 1, Samples 3 and 4 in batch 2, and Samples 5 and 6 in batch 3. +I remove a repeat only when nothing is lost, and log every removal rather than collapsing rows silently. The same name with different values is refused: `duplicate feature names with different values: 'P2' appears more than once. Each feature name must have one set of values.` Two different names with identical values are both kept, since two proteins can quantify to the same numbers. The report's `repeats_removed` column counts the removed rows for each feature (see [Correction report](Correction-Report)). -### Rules +### Scale -- Column names are case-sensitive. `ID`, `sample`, and `batch` must be spelled exactly as shown. -- Every sample name in `ID` must appear as a column in the data matrix. -- Every data matrix column must appear in `ID`. Extra samples in either direction raise a `ValueError`. -- Batch labels must be integers. String labels raise a validation error. -- At least 2 distinct batches are required. A single batch raises a `ValueError`. -- Batch sizes do not need to be equal. Unbalanced batches are handled. +> [!IMPORTANT] +> Both engines treat the location part of a batch effect as a shift added to the values (see [Batch effects](Batch-Effects#why-the-log-scale-matters)), so the values should be log-transformed, usually log2. HarmonizePy does not transform them. Use `log2(x + 1)` for intensities that contain zeros and `log2(x)` otherwise. For proportions such as methylation beta values, correct the M-values, `log2(beta / (1 - beta))`, and convert back for reporting ([Du et al. 2010](References#du-et-al-2010)). -### When passing a DataFrame +A check warns with `harmonizepy.InputScaleWarning` when the values look untransformed: -```python -batch = pd.read_csv("batch.csv") -# No index_col needed. The ID, sample, and batch columns are used by name. -``` +- every value is non-negative and the 95th percentile is above 100, as for raw intensities and counts; or +- every value lies between 0 and 1, with more than two distinct values, as for proportions. ---- +The check is a heuristic. It does not catch percentages from 0 to 100, or raw data that contain a single negative value. `harmonize()` and the command line run it; the engines called directly do not. Silence it in Python with `warnings.filterwarnings("ignore", category=harmonizepy.InputScaleWarning)`. -## Parquet input +## Batch description -If the `harmonizepy[io]` extra is installed, `.parquet` and `.pq` files can be used as data matrix input: +One row per sample. HarmonizePy reads two of its columns: the sample IDs and the batch labels. -```python -result = harmonize("data.parquet", "batch.csv") +```text +ID,sample,batch +s1,1,1 +s2,2,1 +s3,3,1 +s4,4,2 +s5,5,2 +s6,6,2 ``` -The parquet file must have feature names as the index (row labels). Batch description files are always CSV. - ---- - -## Validation errors - -HarmonizePy validates both inputs before running any computation. Common errors and their causes: - -- `"Duplicate feature names in data matrix"`: two or more rows share the same index value -- `"Non-numeric values in data matrix"`: a data cell contains text or a non-numeric value -- `"Sample IDs in description not found in data columns"`: an `ID` value in the batch description does not match any column in the data matrix -- `"Data columns not present in description"`: a data column has no corresponding row in the batch description -- `"batch column must contain integers"`: the `batch` column holds strings or floats -- `"At least 2 batches required"`: all samples share the same batch label -- `"Missing required column: ID"`: the batch description is missing one of the three required columns +- The file is always read as comma-separated, whatever its extension. A tab-separated description is read as one column and refused. +- It must have at least three columns. The IDs come from the column named `ID`, or else the first column; the labels from the column named `batch`, or else the third. Names are case-sensitive. The `sample` column, kept for compatibility with HarmonizR, is never read. It still matters by position: when no column is named `batch`, the batch labels are read from the third column. +- The IDs must be exactly the matrix's column names, each listed once. They are read as text, so an ID such as `01` matches a column named `01`, and a DataFrame column labelled `1` matches the ID `1`. A sample missing from either side is refused, and the message lists the names that do not match. +- Batch labels must be whole numbers: `1`, `1.0` and `"1"` are accepted; text, blanks and fractions such as `1.5` are refused, naming the column. +- Batches can differ in size. A batch of one sample is accepted; ComBat then corrects its groups for location only (see [ComBat](ComBat#the-four-modes)). +- With a single batch there is nothing to correct against. Every feature with at least `needed_values` values keeps them as measured; the others come out empty. + +## Errors + +Validation runs before any correction. On the command line each of these errors is one line starting `ERROR:`, with exit status 1; a missing file is a usage error with status 2 (see [CLI reference](CLI-Reference#exit-status)). + +| Message starts with | Cause | +| ------------------------------------------------------ | --------------------------- | +| `data contains non-numeric columns` | text in a sample column | +| `data contains duplicate sample names` | repeated column name | +| `duplicate feature names with different values` | same name, different values | +| `data contains infinite values` | `inf` or `-inf` in a cell | +| `data contains values of magnitude 1e150 or more` | ComBat with huge values | +| `data must have at least 2 sample columns` | one sample | +| `description must have at least 3 columns` | too few columns | +| `the ID column cannot be found` | first column is the batch | +| `the batch column cannot be found` | third column is the ID | +| `Sample IDs in description do not match data columns` | ID sets differ | +| `sample IDs listed more than once in the description` | repeated ID | +| `batch labels in column 'batch' must be whole numbers` | text, blank or fraction | + +## Related pages + +- [Missing values](Missing-Values): what happens to the gaps in the matrix. +- [CLI reference](CLI-Reference): output formats and the default output path. +- [API reference](API-Reference): passing DataFrames to `harmonize()`. diff --git a/wiki/Installation.md b/wiki/Installation.md index af02023..88321a4 100644 --- a/wiki/Installation.md +++ b/wiki/Installation.md @@ -1,64 +1,54 @@ # Installation -## Requirements +HarmonizePy is a pure-Python package: NumPy and pandas are its only required dependencies, and it needs no R installation. It runs on Python 3.12 or later, and is tested on Linux with Python 3.12, 3.13 and 3.14, and on macOS and Windows with Python 3.12. -- Python 3.12, 3.13, or 3.14 -- numpy >= 1.24 -- pandas >= 2.0 +## From GitHub -No R installation required at runtime. - ---- - -## Install options - -### From PyPI - -```bash -pip install harmonizepy -``` - -### From GitHub (latest development version) +HarmonizePy is not on PyPI yet. Install it from the repository: ```bash pip install git+https://github.com/LangeLab/HarmonizePy.git ``` -### Development install with uv +To add optional extras, name them on the same install: ```bash -uv python install 3.12.13 -uv sync --dev --python 3.12.13 +pip install "harmonizepy[io,config] @ git+https://github.com/LangeLab/HarmonizePy.git" ``` -The `--dev` flag installs pytest, mypy, and ruff alongside the package. +## Optional extras ---- +| Extra | Adds | Needed for | +| ------------ | -------------------- | ------------------------ | +| `io` | `pyarrow >= 14.0` | Parquet input and output | +| `config` | `pyyaml >= 6.0` | YAML config files | +| `completion` | `argcomplete >= 3.0` | shell tab completion | +| `all` | all three | | -## Optional extras +- TOML and JSON config files need no extra; Python reads them itself. +- Without `io`, a `.parquet` or `.pq` path raises an `ImportError` that names the extra. + +## For development -| Extra | Install command | What it adds | -| --- | --- | --- | -| `io` | `pip install harmonizepy[io]` | Parquet output support and faster CSV/TSV reading via `pyarrow >= 14.0` | -| `config` | `pip install harmonizepy[config]` | YAML config files via `pyyaml >= 6.0`. JSON and TOML work without this extra. | -| `completion` | `pip install harmonizepy[completion]` | Shell tab-completion for the CLI via `argcomplete >= 3.0` | -| `all` | `pip install harmonizepy[all]` | All three extras above | +The repository uses [uv](https://docs.astral.sh/uv/), with a lock file: -Parquet is the recommended output format for large datasets. Install the `io` extra if you plan to use `--output-format parquet` or write `.parquet` files directly from Python. +```bash +git clone https://github.com/LangeLab/HarmonizePy.git +cd HarmonizePy +uv sync --dev +uv run pytest +``` ---- +`--dev` adds the test, type-checking and lint tools, among them pytest, mypy and ruff. The tests compare against committed R outputs, so they need no R installation. -## Verify the install +## Check the install ```bash harmonizepy --version ``` -Or from Python: +prints `harmonizepy` and the installed version. From Python, `harmonizepy.__version__` holds the same. -```python -import harmonizepy -print(harmonizepy.__version__) -``` +## Next -Expected output: `0.3.2` +[Quick start](Quick-Start) runs one small matrix from start to finish. diff --git a/wiki/Limits.md b/wiki/Limits.md new file mode 100644 index 0000000..055147b --- /dev/null +++ b/wiki/Limits.md @@ -0,0 +1,41 @@ +# Limits + +HarmonizePy corrects batch effects in a matrix of log-scale values, one affiliation group at a time, using only the batch labels and only the values that were measured. Everything outside that is outside the tool. This page lists the edges, so that a result is not read as more than it is. + +## What it does not do + +- It does not impute. A missing value stays missing, and some measured values become missing (see [Missing values](Missing-Values#missing-values-are-never-filled)). +- It does not transform. Values must already be on a log scale; the scale check is a heuristic warning, not a guarantee (see [Input format](Input-Format#scale)). +- It does not know about biology. The batch label is the only thing read about a sample. There is no argument for a condition, a covariate or a design, so a condition that is unevenly spread over batches is partly removed with the batch (see [Batch effects](Batch-Effects#when-the-batch-is-also-the-biology)). +- It does not anchor groups to a common level. Each affiliation group is corrected toward the mean of its own batches, so features measured in different sets of batches can come out at levels that differ for that reason alone (see [Pipeline](Pipeline#groups-are-corrected-to-their-own-level)). +- It does not correct features it cannot fit. Groups of one feature or one batch, features whose variance is zero under ComBat, and features with no usable batch are returned measured or empty, with the reason in the [correction report](Correction-Report). Under limma, a feature with no spread within its batches is corrected to a single value. +- It does not plot or diagnose. There are no PCA plots or batch-effect scores; besides the matrix, a run gives the report, the log and, on request, a JSON summary. +- It does not store a fit. Each run estimates everything from its own input, so new samples cannot be corrected against an earlier run. + +## What the evidence covers + +> [!IMPORTANT] +> I change a default only when a simulation with a known truth shows the new behaviour is better. Agreement with R is not a reason by itself. That simulation does not exist yet, so no default here claims to be the most accurate choice. + +- The engines and the pipeline are compared against committed outputs of `sva::ComBat`, `limma::removeBatchEffect` and HarmonizR 1.10.0, with stated tolerances (see [R compatibility](R-Compatibility)). Agreement with R shows the same computation, not a correct answer. +- No test checks recovery of a known truth: a matrix where the true batch effects and the true biology are known, before and after correction. The batch-effect tests check that the differences between batch means shrink. +- No measurement here ranks the engines, the modes, the sort strategies or the block sizes on accuracy. The settings pages say what each one does, not which is best. + +## Edges in the engines + +- A batch with one sample: ComBat corrects its groups for location only; limma replaces that sample's values with the feature's mean of batch means (see [limma](limma#edges-worth-knowing)). +- In ComBat, a group with any missing cell uses a different variance rule from a complete group, following `sva::ComBat`, so one missing cell changes every feature of its group (see [ComBat](ComBat#how-a-group-is-corrected)). +- In ComBat, features in the same group affect each other's correction through the shared prior: adding or removing a feature can move the others. + +## Scale + +HarmonizePy holds one matrix in memory and starts no threads of its own. NumPy's linear algebra library can use several cores unless `OMP_NUM_THREADS` and `OPENBLAS_NUM_THREADS` are set to 1, as the benchmarks set them. The benchmark suite has run it on matrices of up to 10,000 features by 100 samples and 5,000 features by 10,000 samples (see [Benchmarks](Benchmarks)). + +## Roadmap + +Planned, not available: accuracy measured against known truth; a common reference level for groups; biological covariates; a result object that stores the fit, so new batches can be corrected against it. + +## Related pages + +- [Correction report](Correction-Report): which features each limit touched in a given run. +- [R compatibility](R-Compatibility): where HarmonizePy and R differ, on purpose. diff --git a/wiki/Missing-Values.md b/wiki/Missing-Values.md new file mode 100644 index 0000000..e59a8e4 --- /dev/null +++ b/wiki/Missing-Values.md @@ -0,0 +1,69 @@ +# Missing values + +In a label-free proteomics matrix, an empty cell mostly does not mean the protein was absent from the sample ([Lazar et al. 2016](References#lazar-et-al-2016)). Most often it means the instrument did not report it: the protein was below the detection limit in that run, or, in data-dependent acquisition, its peptides were not picked for fragmentation that time. Low-abundance proteins come and go between runs, and a batch with lower sensitivity can lose a protein entirely. + +So a matrix holds two kinds of gap, and HarmonizePy treats them differently: + +- a scattered gap, one or a few cells missing in a batch where the feature was otherwise measured; +- a structural gap, in this wiki's usage a feature missing from a whole batch, or with too few values there (fewer than `needed_values`) to estimate anything. + +The first kind is mostly chance; the second often follows abundance, since a protein near the detection limit drops out of the less sensitive runs, so it is missing not at random. + +## Why structural gaps break plain ComBat + +ComBat and limma estimate each feature's effect in each batch from the values it has there. A feature with no value in batch 3 has no batch 3 effect to estimate. `sva::ComBat` stops on such a feature with a singular-matrix error, so `sva::ComBat` cannot correct a matrix with even one protein missing from a whole batch in one piece. Scattered gaps are fine for both engines: each feature is fitted on its observed cells. + +## What HarmonizePy does instead + +Following HarmonizR ([Voss et al. 2022](References#voss-et-al-2022)), it corrects each feature only over the batches where the feature has enough values, and corrects it together with the other features that share exactly those batches. The number of values a feature needs in a batch is `needed_values`: 2 by default for ComBat modes 1 and 3 and for limma, 1 for ComBat modes 2 and 4. The set of batches where a feature reaches it is the feature's affiliation, and features with the same affiliation form one group, corrected as one smaller matrix (see [Pipeline](Pipeline)). + +The [Quick start](Quick-Start) example has eight proteins over three batches of three samples, chosen so that each shows one case: + +

+ + + + The example matrix of eight proteins and nine samples in three batches. Measured cells are coloured by batch, missing cells are empty outlines, and measured cells the run empties are hatched in red: P3 in s7, P4 in s7 to s9, and P6 in s1, s5 and s9. + +

+

Figure 1. The red cells are measured values that do not reach the output. Each one sits in a batch its protein is not corrected over: below needed_values there (P3, P6), or cut by unique removal (P4, whose affiliation on the right, 1, 2, 3, becomes 1, 2).

+ +With `needed_values` 2: + +| Protein | Gap | Affiliation | +| ------- | ---------------------------------------- | ----------- | +| P1 | one cell in batch 1, absent from batch 3 | 1, 2 | +| P2 | absent from batch 3 | 1, 2 | +| P3 | one value in batch 3 | 1, 2 | +| P4 | none | 1, 2, 3 | +| P5 | absent from batch 1 | 2, 3 | +| P6 | one value per batch | none | +| P7 | batch 3 only | 3 | +| P8 | empty | none | + +- P1's missing cell in batch 1 is a scattered gap. Batch 1 still has two values, so it counts, and the cell stays empty in the output. +- P3 has a value in batch 3, but one is below `needed_values`, so batch 3 is outside its affiliation. That value does not reach the output. +- P6 has three values and no batch with two. It comes out empty. + +## Missing values are never filled + +> [!NOTE] +> HarmonizePy does not impute. Every number in the output is a measured value, either corrected or left as measured; none is invented to fill a gap. + +An empty cell in the input is empty in the output, and some measured values become empty too: + +- values in batches outside the feature's affiliation, such as P3's value in batch 3; +- values in batches that [unique removal](Unique-Removal) cut from the feature, such as P4's batch 3 in the default run; +- all values of a feature with no batch that reaches `needed_values`, such as P6. + +The [correction report](Correction-Report) shows this per feature: `batches_used` lists the batches a corrected feature kept, so its values in any other batch are empty, `cropped` marks the features unique removal moved, and `missing_no_usable_batch` marks the rows that are empty throughout. + +## Zeros and infinite values + +A zero is a measured value and is never read as missing. Like any value, it enters its feature's batch mean and spread: if P1's value in `s1` were 0 instead of 20.1, its corrected `s3` would be 24.15 instead of 20.22. On a log scale, a zero intensity becomes minus infinity, and HarmonizePy refuses infinite values with an error that names the feature. Replace them with an empty cell, or use `log2(x + 1)` when the data contain zeros (see [Input format](Input-Format#scale)). + +## Related pages + +- [Pipeline](Pipeline): how affiliations become groups, followed through the same eight proteins. +- [Unique removal](Unique-Removal): how a feature whose affiliation nobody shares can still be corrected. +- [Correction report](Correction-Report): what happened to each feature, and why. diff --git a/wiki/Pipeline.md b/wiki/Pipeline.md index f27704a..5057d29 100644 --- a/wiki/Pipeline.md +++ b/wiki/Pipeline.md @@ -1,131 +1,105 @@ # Pipeline -The `harmonize()` function implements the full HarmonizR-compatible pipeline. This page explains what happens at each stage and why. - ---- - -## The structural missingness problem - -Standard ComBat and limma require fully-dense matrices: every feature must be observed in every sample. Real omics data rarely satisfies this requirement. In proteomics, for example, a peptide may be reliably detected in batches 1 and 2 but absent from batch 3 entirely, not because it was zero but because it was below the detection limit for that instrument run. Treating that absence as NaN and feeding the matrix to ComBat will fail. - -The HarmonizR approach solves this by exploiting the structure of the missingness. Rather than imputing or dropping, it groups features by which batches they appear in, then corrects each group independently using only the batches where that group has data. - ---- - -## Pipeline stages - -### 1. Read and validate - -Inputs are validated before any computation: shapes, column names, types, and sample alignment. A `ValueError` is raised immediately if inputs are inconsistent, not after a long computation. - -### 2. Batch sorting (optional) - -If `sort` is specified, batches are reordered before any other processing. The goal is to place batches with similar data characteristics next to each other. This improves blocking quality (groups of 2 consecutive batches will be more compatible) and can modestly improve correction quality. - -Three strategies are available: - -**`"sparsity"`** - Ranks batches by the fraction of features with data in that batch (completeness). Batches with similar overall completeness become neighbours. This is the fastest of the three strategies. - -**`"jaccard"`** - Ranks batches by pairwise feature-overlap similarity (Jaccard index over which features are observed). More computationally expensive than sparsity. Use it when batch sizes are uneven, because it measures feature overlap rather than just raw completeness counts. - -**`"seriation"`** - Projects batches onto the first principal component of the feature-overlap space and sorts by that coordinate. This is the most computationally expensive sorting option. Use it for datasets with many batches (20+) and complex feature-overlap structure. - -The sorting order affects which features land in which sub-matrix groups after blocking, but it does not change the final correction result for the no-block case (each feature still ends up in a group with the same batches, just potentially in a different order). - -### 3. Blocking (optional) - -If `block=N` is specified, consecutive batches are grouped into blocks of size N before affiliation spotting. Within each block, the batches are treated as a single pool: a feature must have data in enough batches within that block to qualify for adjustment in it. - -Blocking serves two purposes: - -- **Memory reduction**: instead of holding sub-matrices spanning all batches simultaneously, the pipeline processes one block at a time. This is significant for datasets with many batches (SCP cohorts with 20-100 batches). -- **Correction quality**: grouping similar batches reduces the risk that a poorly-matched batch distorts the EB prior for the whole group. - -`block=2` (pairs of consecutive batches) is the standard starting point. Combined with `sort="sparsity"`, it is the recommended configuration for datasets with 5+ batches. - -### 4. Affiliation spotting +Which batches a protein was measured in decides which proteins it is corrected with. `harmonize()` groups every feature by that question, corrects each set of features that share an answer as one smaller matrix, and puts the pieces back in the input's order. The approach is HarmonizR's ([Voss et al. 2022](References#voss-et-al-2022)). This page follows the eight proteins of the [Quick start](Quick-Start) example through it. + +## One feature's way through + +```mermaid +flowchart LR + A[usable
batches] -- none --> M([missing_no_
usable_batch]):::fail + A == 1+ ==> G[its
group] + G -- 1 batch --> R2([raw_single_
batch]) + G -- "1 feature,
2+ batches" --> R1([raw_alone_
in_pattern]) + G == 2+ of each ==> E[engine
fit] + E == fitted ==> OK([corrected]):::ok + E -. set aside .-> R3([raw_zero_variance,
raw_too_few_features,
raw_too_few_values]) + classDef ok fill:#116329,stroke:#4ac26b,color:#ffffff + classDef fail fill:#a40e26,stroke:#ff8182,color:#ffffff + linkStyle default stroke:#8b949e +``` -For each feature, the pipeline determines its **affiliation**: the set of batches (or blocks) in which it has at least `needed_values` non-missing observations. Features with identical affiliations form a group. +

Figure 1. The status each feature ends with in the correction report. The thick line is the path to correction. Only green is corrected; the plain outcomes keep the feature's measured values inside its group's batches, and red empties the row. Unique removal, on by default, runs before groups are formed. A group in one batch is raw_single_batch whatever its size, so P7 ends there.

-A feature that has data in batches 1, 2, and 4 but not batch 3 has a different affiliation from a feature that has data in batches 1, 2, 3, and 4. They will be corrected separately. +## Affiliations -Features with an empty affiliation (not enough data in any batch) are passed through as all-NaN rows. +For each feature, HarmonizePy finds the batches where it has at least `needed_values` measured values ([Missing values](Missing-Values#what-harmonizepy-does-instead) gives the defaults). That set is the feature's affiliation. Features with the same affiliation form a group. -### 5. Unique-combination rescue (unique removal) +With the default settings, the example proteins have these affiliations (the matrix is drawn on [Missing values](Missing-Values)): -Enabled by default (`unique_removal=True`). A feature whose affiliation pattern is unique across the dataset would form a singleton group that ComBat cannot correct (ComBat's EB prior estimation requires multiple features). Without this step, those features would be dropped. +| Protein | Affiliation | After unique removal | +| ---------- | ----------- | -------------------- | +| P1, P2, P3 | 1, 2 | 1, 2 | +| P4 | 1, 2, 3 | 1, 2 | +| P5 | 2, 3 | 2, 3 | +| P6, P8 | none | none | +| P7 | 3 | 3 | -The rescue algorithm crops the feature's affiliation to the nearest shared pattern (the most similar pattern that appears in at least one other feature). This allows the feature to join an existing group and receive a correction, at the cost of losing data from the batches that were cropped out. +P4 is the only protein measured in all three batches. A group of one feature cannot be corrected (ComBat has no other feature to estimate its prior from, and limma would remove the feature's own batch differences, real ones included), so [unique removal](Unique-Removal) moves P4 into the group of P1 to P3 and gives up its batch 3 values. P5's affiliation is also its own, but no other feature's affiliation of two or more batches fits inside it, so it stays alone. -Set `unique_removal=False` only if you need strict missingness-pattern matching and can afford to lose the affected features. +The groups, then, are {P1, P2, P3, P4} over batches 1 and 2, {P5} over batches 2 and 3, and {P7} over batch 3. The dry run reports the same count: -### 6. Sub-matrix extraction +```text + Sub-matrices: 3 (unique affiliation groups) +``` -Features are grouped by their (possibly rescued) affiliation, and one sub-matrix is extracted per group. Each sub-matrix contains exactly the features in that group and the samples from the batches in their shared affiliation. +## Correcting each group -Sub-matrices may still contain per-cell NaN (random missing values within a qualifying batch). These pass through to the correction engines, which handle them per-feature. +

+ + + + Six of the example's eight proteins form three groups: P1 to P4 over batches 1 and 2, P5 over batches 2 and 3, and P7 over batch 3, each with its report status. + +

+

Figure 2. The three groups the default run forms, each a smaller matrix with only its own batches. Only group 1 has two or more features over two or more batches, so only it reaches the engine.

-### 7. Batch correction +Each group becomes a matrix of its features and the samples of its batches, and the engine corrects it alone. Gaps inside the group, such as P1's missing cell in batch 1, go into the engine as gaps: each feature is fitted on the cells it has, and the gap stays empty in the output. -Each sub-matrix is corrected independently by the selected algorithm (ComBat or limma). See [[Algorithms]] for details on how per-cell NaN is handled inside the engines. +A group is fitted only when it has at least two features and at least two batches. The other groups keep their measured values: -Single-feature groups are passed through without adjustment (ComBat requires multiple features for the EB prior). The feature retains its original values rather than being dropped. +- {P7} spans one batch, so there is nothing to correct it against: `raw_single_batch`. +- {P5} has one feature: `raw_alone_in_pattern`. -### 8. Reassembly +Inside a fitted group, ComBat can still set a feature aside, for example one whose variance is zero; those statuses are explained on [Correction report](Correction-Report). -Corrected sub-matrices are scattered back to their original positions in the output matrix. The output has the same shape, index, and column order as the input. Features that were all-NaN in the input remain all-NaN. +HarmonizR drops these features. I keep them with their measured values instead: no value is corrected where its batch effect cannot be estimated, and the report names every such feature, so it is always visible which rows were not corrected. ---- +## The result -## Data flow summary +`harmonize()` returns the matrix with the input's features and sample columns, in the input's order: -```bash -Input matrix (features x samples, may have structural NaN) - | - v -[Sort batches] <- optional: sparsity / jaccard / seriation - | - v -[Form blocks] <- optional: group N consecutive batches - | - v -Spot affiliations <- per feature: which batches have >= needed_values observations - | - v -[Unique removal] <- rescue singleton-affiliation features - | - v -Group by affiliation <- features with identical affiliation -> one sub-matrix - | - v -Correct each sub-matrix <- ComBat or limma, per-cell NaN handled per-feature - | - v -Reassemble <- scatter corrected values back to original positions - | - v -Output matrix (same shape as input, NaN preserved) +```text + s1 s2 s3 s4 s5 s6 s7 s8 s9 +protein +P1 20.67 NaN 20.22 20.69 20.33 21.14 NaN NaN NaN +P2 19.02 19.66 18.57 18.98 19.52 18.35 NaN NaN NaN +P3 23.30 22.58 23.75 23.09 23.54 22.45 NaN NaN NaN +P4 19.84 20.56 19.30 19.77 20.32 19.32 NaN NaN NaN +P5 NaN NaN NaN 16.20 15.80 16.60 17.0 16.4 17.3 +P6 NaN NaN NaN NaN NaN NaN NaN NaN NaN +P7 NaN NaN NaN NaN NaN NaN 24.2 23.6 24.9 +P8 NaN NaN NaN NaN NaN NaN NaN NaN NaN ``` ---- +> [!IMPORTANT] +> The output is not the input with values changed. Measured values outside a feature's group come out empty. -## NaN handling: what is and is not done +Three things in this output are easy to miss: -HarmonizePy never imputes. This is a hard rule. +- It is not the input with values changed. P3's value in `s7` and P4's values in `s7` to `s9` were measured and are now empty, because those batches are outside the group each protein was corrected in. P6 had three values and is empty. +- A feature's correction depends on the rest of its group. Without unique removal, P4 stays raw and the group is P1 to P3 only; P1's value in `s1` is then 20.70 instead of 20.67. Filling P1's one missing cell would change P2 to P4 too, because ComBat uses one variance rule for a group that has any gap and another for a group that has none. +- Only one kind of row is removed: a feature repeated with the same name and the same values appears once (see [Input format](Input-Format#repeated-features)). -**Structural NaN** (a feature absent from an entire batch) is handled by affiliation: that batch is excluded from the feature's group. The correction runs only on batches where the feature has enough data. +## Groups are corrected to their own level -**Per-cell NaN** (a random missing value within a qualifying batch) is handled inside the correction engines using a per-feature computation. For each feature, only the observed samples are used for parameter estimation. The NaN positions in the output match the NaN positions in the input exactly. +Each group is corrected toward the mean of its own batches. A feature corrected over batches 1 and 2 ends near its batch 1 and 2 average; a feature corrected over batches 1, 2 and 3 ends near its average over all three. When batch 3 reads higher or lower than the others, two features with the same true level can come out at different levels partly because they were measured in different batches. Comparisons within a feature, between samples, are what the correction is for; comparisons of levels between features with different affiliations carry this offset (see [Limits](Limits)). -If a feature has no qualifying affiliation group after all the steps above, it appears as an all-NaN row in the output. It is never filled with imputed or carry-forward values. +## Many batches: sorting and blocking ---- +With many batches and much missing data, features scatter over many small groups. `block` groups neighbouring batches so that affiliations are formed over fewer, larger units, and `sort` decides which batches are neighbours. Blocking trades measured values for larger groups, and sorting decides which batches share a block; they are explained on [Sorting and blocking](Sorting-and-Blocking). -## Choosing pipeline parameters +## Related pages -- Small dataset, 2-4 batches: default (no `sort`, no `block`) -- 5-10 batches, bulk proteomics: `sort="sparsity"`, `block=2` -- 10+ batches, uneven batch sizes: `sort="jaccard"`, `block=2` -- Many batches, complex overlap structure: `sort="seriation"`, `block=2` -- To retain the most features: keep `unique_removal=True` (default) -- Strict missingness-pattern matching: `unique_removal=False` +- [Unique removal](Unique-Removal): the rule that moved P4, and when it finds nothing. +- [Correction report](Correction-Report): reading the status of every feature after a run. +- [ComBat](ComBat) and [limma](limma): what happens inside one group. diff --git a/wiki/Quick-Start.md b/wiki/Quick-Start.md index 1faa0a1..c5d935a 100644 --- a/wiki/Quick-Start.md +++ b/wiki/Quick-Start.md @@ -1,133 +1,148 @@ -# Quick Start +# Quick start -## The simplest case +One small matrix, from files to a corrected result, with the real output of every step. The same proteins appear throughout this wiki, so the cases met here (a protein missing from a batch, one measured in every batch, one with too few values anywhere) are explained there in full. -If you have a TSV data matrix and a batch description CSV, pass the file paths directly: +## 1. Two input files -```python -from harmonizepy import harmonize +The data matrix: features in rows, samples in columns, log2 values, empty cells for missing values. Save it as `proteins.tsv` (tab-separated): -result = harmonize("data.tsv", "batch.csv") +```text +protein s1 s2 s3 s4 s5 s6 s7 s8 s9 +P1 20.1 19.6 21.3 20.9 21.8 +P2 18.2 18.9 17.7 19.8 20.4 19.1 +P3 22.5 21.7 23.0 23.9 24.4 23.2 21.1 +P4 19.0 19.8 18.4 20.6 21.2 20.1 17.9 18.6 18.1 +P5 16.2 15.8 16.6 17.0 16.4 17.3 +P6 20.5 21.0 19.2 +P7 24.2 23.6 24.9 +P8 ``` -`result` is a `pandas.DataFrame` with features as rows and samples as columns. The shape and column order match the input exactly. Missing values stay missing. - ---- - -## From DataFrames - -If you have already loaded your data, pass DataFrames directly: - -```python -import pandas as pd -from harmonizepy import harmonize - -data = pd.read_csv("data.tsv", sep="\t", index_col=0) -batch = pd.read_csv("batch.csv") - -result = harmonize(data, batch) +The batch description: one row per sample, with its batch. Save it as `batches.csv`: + +```text +ID,sample,batch +s1,1,1 +s2,2,1 +s3,3,1 +s4,4,2 +s5,5,2 +s6,6,2 +s7,7,3 +s8,8,3 +s9,9,3 ``` -The `data` DataFrame must have feature names in the index and sample names as columns. See [[Input-Format]] for the exact requirements. +The `sample` column is not read, but the file needs three columns (see [Input format](Input-Format)). ---- +## 2. Check the plan -## Writing output to a file +`--dry-run` reads and validates both files and plans the run without correcting or writing anything: -Pass `output_file` to write the result without a separate save step: - -```python -result = harmonize("data.tsv", "batch.csv", output_file="corrected.tsv") +```bash +harmonizepy proteins.tsv batches.csv --dry-run ``` -Supported formats: `.tsv`, `.csv`, `.parquet`, `.pq`. Parquet requires the `harmonizepy[io]` extra. - ---- - -## Choosing an algorithm - -The default is ComBat mode 1 (parametric, location + scale). This handles the majority of bulk-proteomics and microarray datasets well. - -```python -# Default: ComBat mode 1 -result = harmonize(data, batch) - -# limma: faster, linear-model correction. Good for a quick check or pre-scaled data. -result = harmonize(data, batch, algorithm="limma") - -# ComBat mode 3: non-parametric. Better for small batches (fewer than ~10 samples per batch). -result = harmonize(data, batch, combat_mode=3) +
+Output: the plan, 3 sub-matrices + +```text + HarmonizePy 0.4.0 dry run + ---------------------------------------------------- + Input data: proteins.tsv + Description: batches.csv + Output: proteins_corrected.tsv [tsv] + ---------------------------------------------------- + Features: 8 + Samples: 9 + Batches: 3 + Sub-matrices: 3 (unique affiliation groups) + ---------------------------------------------------- + Algorithm: ComBat mode 1 + needed_values: 2 + Sort strategy: none + Block size: none (each batch is its own block) + Unique removal: enabled + ---------------------------------------------------- + Inputs valid. Use without --dry-run to run correction. ``` -See [[Algorithms]] for a full comparison of all modes and guidance on when to switch. - ---- +
-## Datasets with many batches: add sorting and blocking +`needed_values` is the number of values a protein needs in a batch for that batch to count (2 here). The batches that count for a protein are its affiliation, and proteins with the same affiliation form a group, which the dry run calls a sub-matrix. Three sub-matrices: six of the eight proteins fall into three groups by the batches they have enough values in, and the other two have no such batch. [Pipeline](Pipeline) shows which. -For datasets with 5 or more batches, adding `sort` and `block` improves both runtime and correction quality: +## 3. Run it -```python -result = harmonize( - data, - batch, - sort="sparsity", - block=2, -) +```bash +harmonizepy proteins.tsv batches.csv --report report.tsv ``` -`sort="sparsity"` reorders batches so that those with similar completeness sit next to each other. `block=2` then groups every 2 consecutive batches into a single sub-matrix before running adjustment. This reduces peak memory and can improve correction stability when individual batches are small. - -See [[Pipeline]] for a conceptual explanation of what sorting and blocking do. - ---- - -## Reproducible runs with HarmonizeConfig - -To save and reuse a run configuration: - -```python -from harmonizepy import harmonize, HarmonizeConfig - -cfg = HarmonizeConfig( - algorithm="ComBat", - combat_mode=1, - sort_strategy="sparsity", - block_size=2, -) - -result = harmonize(data, batch, config=cfg) +```text +INFO [harmonizepy] Input: 8 features x 9 samples +INFO [harmonizepy] Algorithm: ComBat mode 1 | batches: 3 | needed_values: 2 +INFO [harmonizepy] Unique removal moved 1 feature(s) into a shared pattern (12.5%) +INFO [harmonizepy] Adjusting 3 unique affiliation group(s) +INFO [harmonizepy] 2 feature(s) passed through without correction (1 in single-batch groups, 1 alone in their pattern) +INFO [harmonizepy] Done (0.00s). +INFO [harmonizepy] Output written to proteins_corrected.tsv +INFO [harmonizepy] Report written to report.tsv ``` -When `config` is provided, all individual keyword arguments (`algorithm`, `sort`, `block`, etc.) are ignored. See [[API-Reference]] for the full `HarmonizeConfig` field list. +The run writes its files next to the input: ---- +| File | Written | +| --- | --- | +| `proteins_corrected.tsv` | always | +| `proteins_corrected.log` | unless `--no-log` | +| `report.tsv` | with `--report` | -## Low-level API: direct engine access - -For cases where you manage batches yourself or work with NumPy arrays: +## 4. The same run from Python ```python -import numpy as np -from harmonizepy import combat, remove_batch_effect +from harmonizepy import harmonize -# data_matrix: (n_features, n_samples) float64 ndarray -# batch_labels: 1-D array of integer batch labels, length n_samples +result, report = harmonize("proteins.tsv", "batches.csv", return_report=True) +print(result.round(2)) +``` -corrected = combat(data_matrix, batch_labels) -corrected = remove_batch_effect(data_matrix, batch_labels) +```text + s1 s2 s3 s4 s5 s6 s7 s8 s9 +protein +P1 20.67 NaN 20.22 20.69 20.33 21.14 NaN NaN NaN +P2 19.02 19.66 18.57 18.98 19.52 18.35 NaN NaN NaN +P3 23.30 22.58 23.75 23.09 23.54 22.45 NaN NaN NaN +P4 19.84 20.56 19.30 19.77 20.32 19.32 NaN NaN NaN +P5 NaN NaN NaN 16.20 15.80 16.60 17.0 16.4 17.3 +P6 NaN NaN NaN NaN NaN NaN NaN NaN NaN +P7 NaN NaN NaN NaN NaN NaN 24.2 23.6 24.9 +P8 NaN NaN NaN NaN NaN NaN NaN NaN NaN ``` -Both functions return an ndarray of the same shape as the input. NaN positions are preserved. These functions do not handle structural missingness: for that, use `harmonize()`. +`harmonize()` also takes DataFrames: the matrix with feature names as the index (`pd.read_csv("proteins.tsv", sep="\t", index_col=0)`) and the description with no index (`pd.read_csv("batches.csv")`). ---- +## 5. What happened to each protein -## CLI +```text +protein status batches_used group_size cropped repeats_removed +P1 corrected 1,2 4 False 0 +P2 corrected 1,2 4 False 0 +P3 corrected 1,2 4 False 0 +P4 corrected 1,2 4 True 0 +P5 raw_alone_in_pattern 1 False 0 +P6 missing_no_usable_batch 0 False 0 +P7 raw_single_batch 1 False 0 +P8 missing_no_usable_batch 0 False 0 +``` -The same pipeline is available from the terminal: +- P1 to P4 were corrected together over batches 1 and 2. Their batch gap of about 1.5 shrank to between 0.1 and 0.3 ([Batch effects](Batch-Effects#what-correction-does-to-it)). +- P4 was measured in all three batches and was moved into that group by [unique removal](Unique-Removal); its batch 3 values are now empty. +- P3's single value in batch 3 is below `needed_values` (2 values per batch by default), so batch 3 is not part of its correction, and that value is empty too. +- P5 and P7 kept their measured values: no other protein has enough values in exactly their batches. +- P6 and P8 are empty: neither has two values in any batch. -```bash -harmonizepy data.tsv batch.csv -o corrected.tsv -``` +## Where next -See [[CLI-Reference]] for all options. +- Your own data: [Input format](Input-Format) for what the two files must hold, and the log scale the values should be on. +- Settings: [Choosing an engine](Algorithms), and [Sorting and blocking](Sorting-and-Blocking) for many batches. +- Reading results: [Correction report](Correction-Report). +- Everything the command takes: [CLI reference](CLI-Reference); the Python functions: [API reference](API-Reference). diff --git a/wiki/R-Compatibility.md b/wiki/R-Compatibility.md index 02b8614..e86f8bf 100644 --- a/wiki/R-Compatibility.md +++ b/wiki/R-Compatibility.md @@ -1,98 +1,116 @@ -# R Compatibility +# R compatibility -HarmonizePy is validated against three R reference implementations: +HarmonizePy is checked against the R packages it reimplements ([Leek et al. 2012](References#leek-et-al-2012); [Ritchie et al. 2015](References#ritchie-et-al-2015); [HarmonizR 1.10.0](References#harmonizr-1100)): `sva::ComBat` 3.60.0, `limma::removeBatchEffect` and HarmonizR 1.10.0, pinned in the repository's `renv.lock`. Matching R is a check that the computation is the same, not the goal itself. -- `sva::ComBat` (Bioconductor sva v3.60.0) -- `limma::removeBatchEffect` (Bioconductor limma) -- `HarmonizR` v1.10.0 (Bioconductor) +> [!NOTE] +> Agreement with R shows that HarmonizePy computes what R computes. It is not evidence that either result is correct. I keep it as a regression check, and do not change HarmonizePy just to match R. Where HarmonizePy behaves differently on purpose, the difference and its reason are listed below. -This page describes what is validated, the numerical tolerances achieved, and the known differences between HarmonizePy and the R implementations. +## How the comparison works ---- +The R outputs are generated once by scripts in `tests/fixtures/` and committed. The test suite runs the Python code on the same inputs and compares cell by cell with `numpy.testing.assert_allclose`, so the comparison runs in CI without R installed. Engine tests compare `combat()` and `remove_batch_effect()` with `sva` and `limma`; pipeline tests compare `harmonize()` with HarmonizR, including sorting, blocking, unique removal and `needed_values`, and check that the missing cells sit in the same places. -## Validation scope +## Tolerances -The parity validation covers: +The tolerances the tests assert, as relative and absolute tolerance: -- All four ComBat modes and limma on dense synthetic data -- Per-cell NaN handling on real murine medulloblastoma data (4753 features, 25 samples, 4 batches, 49% missing) -- DIA proteomics data (8470 features, 36 samples, 2 batches) -- Full pipeline: blocking, sort+block, `unique_removal` toggle, and the combined stress case (sort + block + unique_removal + per-cell NaN) -- Synthetic datasets at small, medium, and SCP-scale +| Comparison | rtol | atol | +| -------------------------- | ------------- | ------------- | +| limma, engine and pipeline | 1e-8 to 1e-10 | 1e-8 to 1e-10 | +| ComBat modes 2 and 4 | 1e-6 to 1e-4 | 1e-8 to 1e-4 | +| ComBat mode 1 | 1e-4 to 5e-4 | 1e-6 to 1e-4 | +| ComBat mode 3 | 1e-6 to 5e-4 | 1e-8 to 1e-4 | ---- +- The range in each row covers the different fixtures: dense, sparse, high-missingness, blocked and sorted inputs. +- limma is a closed-form least-squares fit, so it agrees to rounding. ComBat mode 1 iterates to a convergence threshold of $`10^{-4}`$, with a slightly different stopping test from `sva` (see [ComBat](ComBat#parametric-and-non-parametric-priors)), so it agrees to about that threshold. +- The benchmark suite compares against HarmonizR on larger matrices as well; its results are in [Benchmarks](Benchmarks). -## Concordance table +## Where HarmonizePy differs on purpose -| Method | Dense tolerance | Murine real data (max_rel) | NaN positions match | -| --- | --- | --- | --- | -| ComBat mode 1 (parametric, loc+scale) | 2e-5 | 0.0003 | Yes | -| ComBat mode 2 (parametric, loc only) | 1e-9 | 0.0000 | Note 1 | -| ComBat mode 3 (non-parametric, loc+scale) | 5e-4 | 0.0000 | Yes | -| ComBat mode 4 (non-parametric, loc only) | 1e-9 | 0.0000 | Note 1 | -| limma removeBatchEffect | 1e-9 | 0.0000 | Yes | +### Features are kept -**Note 1:** Modes 2 and 4 with R: R drops 229 additional features due to an interaction between `mean_only=TRUE` and single-feature groups. HarmonizePy retains those features as all-NaN rows. On the shared subset of features, values match perfectly (0.0000). +HarmonizR removes some features from its output. I keep every input feature except an exact repeat, so the output has one row per input feature whatever the data: ---- +- A feature alone in its affiliation, over two or more batches: HarmonizR does not return it as measured. In the benchmarks it drops such features; on the [Quick start](Quick-Start) example it keeps P5 but empties its batch 2 values. HarmonizePy returns its measured values (`raw_alone_in_pattern`). +- A feature with no usable batch: R drops it; HarmonizePy returns an empty row (`missing_no_usable_batch`). -## Known behavioral differences +The [correction report](Correction-Report) says which rows were not corrected. To get HarmonizR's shape for a comparison, drop the empty rows yourself: -The following differences are intentional. None affect the corrected values for features that both implementations process. +```python +result = harmonize("data.tsv", "batch.csv") +result = result.dropna(how="all") +``` -### Single-feature groups +### A feature missing a whole batch -A feature with a batch-presence pattern that appears only once (singleton group) has no other features to share the ComBat EB prior with. R drops the feature entirely. HarmonizePy keeps it with its original (uncorrected) values. +Called directly on such a feature, `sva::ComBat` stops with a singular-matrix error; `combat()` fits it on the batches it has. `limma::removeBatchEffect` sets the coefficient it cannot estimate to zero; `remove_batch_effect()` fits contrasts over the batches the feature has. For a feature missing an interior batch the two limma versions agree; for one missing the first or last batch they differ (see [limma](limma#missing-cells)). Inside `harmonize()` the case does not arise, because every feature has values in every batch of its group. -**When this occurs:** only when exactly 1 feature has a given batch-presence pattern and that pattern involves 2 or more batches. On the murine dataset (4753 features), this never occurs. On a medium synthetic dataset (5000 features), it affects roughly 32 of 4968 features. +### Constant features -**Practical effect:** the affected features retain their original batch effects. They appear in the output and can be filtered downstream if needed. The correction of all other features is unaffected. +Both leave rows that cannot be scaled out of the ComBat fit and return them unadjusted, with different tests: -### All-NaN rows for unqualified features +- `sva` leaves out a row whose variance is exactly zero in any batch of two or more samples, in every mode. Its test takes the variance without removing missing cells, so a row with a missing cell is never left out, and such a row can make `sva::ComBat` stop with an error. +- HarmonizePy leaves out, in every mode, a row whose pooled variance is below $`10^{-12}`$, and in mode 1 also a row whose variance in a batch with two or more values is below $`10^{-12}`$ of its pooled variance. Near-constant rows are therefore left out too, and rows with missing cells are tested like any other. -Features with no qualifying batch (below the `needed_values` threshold in every batch) appear as all-NaN rows in the HarmonizePy output. R omits these features from the output entirely, producing a matrix with fewer rows. +### Unique removal -**Practical effect:** the output matrix shape differs by the number of such features. The HarmonizePy convention produces a predictable output shape that matches the input regardless of data quality. +Both move a feature with a pattern of its own into the longest pattern of another feature inside its own, even one held by a single feature (see [Unique removal](Unique-Removal)); `(1,2,3,4), (1,2), (5,6), (5,6)` becomes `(1,2), (1,2), (5,6), (5,6)` in both. They differ in three ways: HarmonizR walks the features in row order and takes the first of equally long targets, where HarmonizePy takes the longest patterns first and breaks ties by group size, then the smallest pattern; HarmonizR empties a feature with no target, where HarmonizePy keeps its measured values; and HarmonizR accepts a target of one batch, which HarmonizePy refuses. -### Input validation strictness +### Sort orders -R silently coerces non-numeric cells to NA and silently deduplicates rows with identical identifiers. HarmonizePy raises a `ValueError` in both cases. This is intentional: silent coercion can mask data preparation errors. +All three sort strategies can order batches differently from HarmonizR, whose rules differ: -### Sorting algorithm differences +| Strategy | HarmonizePy | HarmonizR | +| ----------- | --------------------------- | -------------------------- | +| `sparsity` | most present features first | fewest missing cells first | +| `jaccard` | nearest-neighbour chain | pairs, then chained | +| `seriation` | first principal component | `seriation::seriate` | -Jaccard and seriation sorting strategies produce different batch orderings from their R equivalents. The R versions use exact pairwise-similarity chaining (jaccard) and hierarchical optimal-leaf-ordering via `seriation::seriate` (seriation). HarmonizePy uses nearest-neighbour chaining (jaccard) and PCA-based ordering (seriation). +Sorting changes the output only together with blocking (see [Sorting and blocking](Sorting-and-Blocking)). -In practice, both jaccard and sparsity sort produce identical batch orderings across all tested configurations. The seriation divergence produces a different ordering, but correction quality is within the same range. These algorithms are explicitly not required to match R exactly. +### Input handling -### Default output filename +- A cell that is not a number: R turns it into a missing value; HarmonizePy refuses the column. +- Repeated rows: R removes rows whose values repeat another row, whatever their names; HarmonizePy removes a row only when its name and its values repeat, logs it, and refuses a repeated name with different values. +- Empty rows and columns: R removes them; HarmonizePy keeps them. +- Columns of the output: R returns only the columns of the groups it corrected, in the order of the groups, so a batch that no group uses has no columns in its output; HarmonizePy returns every input column, in the input order. +- The batch description: R reads its columns by position; HarmonizePy reads the columns named `ID` and `batch`, and falls back to position. +- `needed_values`: HarmonizePy takes it as an argument, with HarmonizR's defaults for ComBat. +- Output file: R writes `cured_data.tsv`; the `harmonizepy` command writes `_corrected.tsv` next to the input, and `harmonize()` writes only to `output_file`. -R writes `cured_data.tsv`. HarmonizePy writes `_corrected.tsv` next to the input file. +## Where HarmonizR is the better choice ---- +- Reproducing a published HarmonizR result exactly: the unique-removal rule and the sort orders differ, so some features land in different groups. +- Wanting HarmonizR's output shape: it removes features it does not correct, where HarmonizePy keeps them (`result.dropna(how="all")` removes the empty rows, but raw features stay). +- Working in R: HarmonizR accepts and returns S4 objects, plots, and can run its groups on several cores. -## Verifying against your own R results +## Not provided -If you want to compare HarmonizePy output against R on your own data, the simplest approach is to run the same data through R `HarmonizR::harmonizR()` and compare the outputs feature by feature. +HarmonizR's S4 objects, plotting, and multi-core execution have no counterpart. HarmonizePy starts no threads or processes of its own. -A typical comparison in Python: +## Comparing with your own R run + +To compare a HarmonizePy result with a HarmonizR result on the same input, align the two on their shared features and samples, compare the cells both have, and count the features only one side returns: ```python -import pandas as pd import numpy as np +import pandas as pd -py_result = pd.read_csv("harmonizepy_output.tsv", sep="\t", index_col=0) -r_result = pd.read_csv("harmonizr_output.tsv", sep="\t", index_col=0) +py = pd.read_csv("data_corrected.tsv", sep="\t", index_col=0) +r = pd.read_csv("cured_data.tsv", sep="\t", index_col=0) -# Align on shared features and samples -shared = py_result.index.intersection(r_result.index) -py = py_result.loc[shared] -r = r_result.loc[shared] +rows = py.index.intersection(r.index) +cols = py.columns.intersection(r.columns) +a, b = py.loc[rows, cols].to_numpy(), r.loc[rows, cols].to_numpy() -# Max relative difference on non-NaN cells -rel_diff = np.abs(py.values - r.values) / (np.abs(r.values) + 1e-10) -print(f"Max relative difference: {np.nanmax(rel_diff):.2e}") -print(f"Features only in Python output: {len(py_result) - len(shared)}") -print(f"Features only in R output: {len(r_result) - len(shared)}") +both = ~np.isnan(a) & ~np.isnan(b) +print("max relative difference:", np.max(np.abs(a[both] - b[both]) / np.abs(b[both]))) +print("missing cells differ:", int((np.isnan(a) != np.isnan(b)).sum())) +print("features only in HarmonizePy:", len(py.index.difference(r.index))) ``` -A `max_rel` below `5e-4` on ComBat mode 1 (and below `1e-9` on modes 2, 3, 4 and limma) is concordant with the reference validation results. Features present only in the Python output are the single-feature pass-through and all-NaN retention cases described above. +Features only in the HarmonizePy output are the kept features described above, and rows R removed as value repeats. A difference in missing cells on shared features comes from unique removal, from the sort order with blocking, or from HarmonizR returning whole features missing, which the benchmarks show in some ComBat modes (see [Benchmarks](Benchmarks#reading-the-concordance)). + +## Related pages + +- [Benchmarks](Benchmarks): concordance on larger and real matrices. +- [Limits](Limits): what agreement with R does and does not show. diff --git a/wiki/References.md b/wiki/References.md new file mode 100644 index 0000000..bd5a615 --- /dev/null +++ b/wiki/References.md @@ -0,0 +1,81 @@ +# References + +The papers and packages this wiki relies on, grouped by what they are used for. Pages cite them as author and year, linked to the entry here. Each entry gives the full reference and its DOI. + +## Methods + +### Johnson et al. 2007 + +Johnson WE, Li C, Rabinovic A. Adjusting batch effects in microarray expression data using empirical Bayes methods. *Biostatistics* 8(1):118-127, 2007. doi:[10.1093/biostatistics/kxj037](https://doi.org/10.1093/biostatistics/kxj037) + +The ComBat model and its parametric and non-parametric empirical Bayes estimates. Cited on [ComBat](ComBat) and [Choosing an engine](Algorithms). + +### Leek et al. 2012 + +Leek JT, Johnson WE, Parker HS, Jaffe AE, Storey JD. The sva package for removing batch effects and other unwanted variation in high-throughput experiments. *Bioinformatics* 28(6):882-883, 2012. doi:[10.1093/bioinformatics/bts034](https://doi.org/10.1093/bioinformatics/bts034) + +The `sva` package, whose `ComBat` function HarmonizePy is checked against, including its `par.prior` and `mean.only` switches. Cited on [ComBat](ComBat) and [R compatibility](R-Compatibility). + +### Ritchie et al. 2015 + +Ritchie ME, Phipson B, Wu D, Hu Y, Law CW, Shi W, Smyth GK. limma powers differential expression analyses for RNA-sequencing and microarray studies. *Nucleic Acids Research* 43(7):e47, 2015. doi:[10.1093/nar/gkv007](https://doi.org/10.1093/nar/gkv007) + +The reference for the `limma` package, which provides `removeBatchEffect`. The function's own documentation cites no separate paper. Cited on [limma](limma). + +## HarmonizR + +### Voss et al. 2022 + +Voss H, Schlumbohm S, Barwikowski P, Wurlitzer M, Dottermusch M, Neumann P, Schlueter H, Neumann JE, Krisp C. HarmonizR enables data harmonization across independent proteomic datasets with appropriate handling of missing values. *Nature Communications* 13:3523, 2022. doi:[10.1038/s41467-022-31007-x](https://doi.org/10.1038/s41467-022-31007-x) + +The HarmonizR approach: splitting a matrix by missing-value pattern and correcting each part with ComBat or limma, without imputation. Cited on [Home](Home), [Missing values](Missing-Values) and [Pipeline](Pipeline). + +### Schlumbohm et al. 2025 + +Schlumbohm S, Neumann JE, Neumann P. HarmonizR: blocking and singular feature data adjustment improve runtime efficiency and data preservation. *BMC Bioinformatics* 26:47, 2025. doi:[10.1186/s12859-025-06073-9](https://doi.org/10.1186/s12859-025-06073-9) + +Blocking, batch sorting and unique removal in HarmonizR. Cited on [Unique removal](Unique-Removal) and [Sorting and blocking](Sorting-and-Blocking). + +### HarmonizR 1.10.0 + +Schlumbohm S, Neumann JE, Neumann P. HarmonizR, Bioconductor package, version 1.10.0. [Bioconductor](https://bioconductor.org/packages/release/bioc/html/HarmonizR.html); source at [HSU-HPC/HarmonizR](https://github.com/HSU-HPC/HarmonizR). + +The release HarmonizePy's pipeline tests compare against. Cited on [R compatibility](R-Compatibility). + +## Batch effects and missing values + +### Leek et al. 2010 + +Leek JT, Scharpf RB, Bravo HC, Simcha D, Langmead B, Johnson WE, Geman D, Baggerly K, Irizarry RA. Tackling the widespread and critical impact of batch effects in high-throughput data. *Nature Reviews Genetics* 11(10):733-739, 2010. doi:[10.1038/nrg2825](https://doi.org/10.1038/nrg2825) + +How common batch effects are, and how they can outweigh the biology a study measures. Cited on [Batch effects](Batch-Effects). + +### Cuklina et al. 2021 + +Cuklina J, Lee CH, Williams EG, Sajic T, Collins BC, Rodriguez Martinez M, Sharma VS, Wendt F, Goetze S, Keele GR, Wollscheid B, Aebersold R, Pedrioli PGA. Diagnostics and correction of batch effects in large-scale proteomic studies: a tutorial. *Molecular Systems Biology* 17(8):e10240, 2021. doi:[10.15252/msb.202110240](https://doi.org/10.15252/msb.202110240) + +Sources of batch effects in proteomics, and how to diagnose them. Cited on [Batch effects](Batch-Effects). + +### Rocke and Durbin 2001 + +Rocke DM, Durbin B. A model for measurement error for gene expression arrays. *Journal of Computational Biology* 8(6):557-569, 2001. doi:[10.1089/106652701753307485](https://doi.org/10.1089/106652701753307485) + +Measurement error that grows with the signal, the reason for working on a log scale. Cited on [Batch effects](Batch-Effects). + +### Nygaard et al. 2016 + +Nygaard V, Rodland EA, Hovig E. Methods that remove batch effects while retaining group differences may lead to exaggerated confidence in downstream analyses. *Biostatistics* 17(1):29-39, 2016. doi:[10.1093/biostatistics/kxv027](https://doi.org/10.1093/biostatistics/kxv027) + +What batch correction does when batches and conditions are unevenly mixed. Cited on [Batch effects](Batch-Effects). + +### Lazar et al. 2016 + +Lazar C, Gatto L, Ferro M, Bruley C, Burger T. Accounting for the multiple natures of missing values in label-free quantitative proteomics data sets to compare imputation strategies. *Journal of Proteome Research* 15(4):1116-1125, 2016. doi:[10.1021/acs.jproteome.5b00981](https://doi.org/10.1021/acs.jproteome.5b00981) + +Why values are missing in label-free proteomics: below detection (missing not at random) or by chance (missing completely at random). Cited on [Missing values](Missing-Values). + +### Du et al. 2010 + +Du P, Zhang X, Huang CC, Jafari N, Kibbe WA, Hou L, Lin SM. Comparison of Beta-value and M-value methods for quantifying methylation levels by microarray analysis. *BMC Bioinformatics* 11:587, 2010. doi:[10.1186/1471-2105-11-587](https://doi.org/10.1186/1471-2105-11-587) + +M-values, the log-ratio scale for methylation proportions. Cited on [Input format](Input-Format). diff --git a/wiki/Sorting-and-Blocking.md b/wiki/Sorting-and-Blocking.md new file mode 100644 index 0000000..10a2e3e --- /dev/null +++ b/wiki/Sorting-and-Blocking.md @@ -0,0 +1,68 @@ +# Sorting and blocking + +With twenty batches and patchy coverage, proteins scatter over hundreds of small affiliation groups, many of them too small to correct well. Blocking makes the unit of affiliation a block of neighbouring batches instead of a single batch, so there are fewer possible patterns and larger groups. Sorting decides which batches are neighbours. Both come from HarmonizR ([Schlumbohm et al. 2025](References#schlumbohm-et-al-2025)), and both are off by default. + +## Blocking + +`block=N` (`--block N`) takes the batches in their order, after sorting if `sort` is set, and puts every N of them in one block. When the number of batches is not a multiple of N, the last block is smaller. N must be at least 2 and smaller than the number of batches, since a single block holding every batch would leave nothing to correct. + +A block counts for a feature only when every batch inside it has at least `needed_values` values of the feature. Affiliations, groups and unique removal then work on blocks. The engine still corrects each original batch inside a group: blocking changes who is grouped with whom, not what a batch is. + +The cost is measured values. A feature missing from one batch of a block loses the whole block. In the [Quick start](Quick-Start) example with `block=2`, batches 1 and 2 form block 1 and batch 3 forms block 2. P5 is measured in batches 2 and 3; block 1 fails for it because batch 1 is empty, so P5 keeps only batch 3: + +

+ + + + Protein P5 over three batches, without blocking and with block=2. Without blocking, batches 2 and 3 count. With block=2, batches 1 and 2 form one block, which fails because batch 1 is empty, so P5's batch 2 values are hatched as lost. + +

+

Figure 1. A block counts only when every batch in it has enough values. Batch 1 is empty for P5, so the block of batches 1 and 2 fails, and P5's three measured values in batch 2 go with it.

+ +| Run | P5 status | P5 values kept | +| --------- | ---------------------- | -------------- | +| no block | `raw_alone_in_pattern` | s4 to s9 | +| `block=2` | `raw_single_batch` | s7 to s9 | + +Whether the larger groups are worth the lost values depends on the data, and no measurement here gives a block size that suits most data. The dry run's sub-matrix count and the report's status counts, with and without blocking, show the trade on a given matrix. + +## How the two options combine + +```mermaid +flowchart LR + Q{block set?} -- no --> A1([affiliations over
batches; sort has
no effect]):::ok + Q == yes ==> S["sort, when set"]:::opt + Q -. yes, no sort .-> K + S ==> K[N neighbouring
batches per block] + K ==> A2([affiliations
over blocks]):::ok + classDef opt stroke:#8b949e,stroke-width:1.5px,stroke-dasharray:4 3 + classDef ok fill:#116329,stroke:#4ac26b,color:#ffffff + linkStyle default stroke:#8b949e +``` + +

Figure 2. Sorting matters only on the blocked path, where it decides which batches share a block. The dashed box runs only when sort is given.

+ +## Sorting + +`sort` (`--sort`) reorders the batches before blocking so that batches with similar coverage sit next to each other, and so more often share a block. Each strategy works from which features are present in each batch, where present means at least `needed_values` values: + +| Strategy | Order | +| ----------- | --------------------------------------------- | +| `sparsity` | most present features first | +| `jaccard` | nearest-neighbour chain on Jaccard similarity | +| `seriation` | score on the first principal component | + +- `jaccard`: the similarity of two batches is the number of features present in both over the number present in either. The chain starts at the batch most similar to all the others and moves each time to the most similar batch not yet placed. +- `seriation`: batches are scored on the first principal component of their presence vectors, centred per feature and not scaled. The component is computed exactly, so the order does not depend on the order of the rows, and batches with equal scores keep their input order. + +Sorting changes the result only together with blocking. Without `block`, every sort gives exactly the same output as no sort, because affiliations over single batches do not depend on their order. The output keeps the input's column order either way. + +In the example, the presence counts are 4, 5 and 3 for batches 1, 2 and 3, so `sort="sparsity"` orders them 2, 1, 3. With `block=2` the blocks are {2, 1} and {3}, the same grouping as without sorting, so the output does not change. + +All three strategies can order batches differently from HarmonizR, whose rules for each differ (see [R compatibility](R-Compatibility)). No measurement here shows one strategy correcting better than another. + +## Related pages + +- [Pipeline](Pipeline): affiliations and groups, which blocking changes. +- [Unique removal](Unique-Removal): with blocks, it crops blocks. +- [CLI reference](CLI-Reference): the `--sort`, `--block` and `--dry-run` flags. diff --git a/wiki/Unique-Removal.md b/wiki/Unique-Removal.md new file mode 100644 index 0000000..5006c43 --- /dev/null +++ b/wiki/Unique-Removal.md @@ -0,0 +1,65 @@ +# Unique removal + +A protein measured in a set of batches that no other protein shares would form a group of one, and a group of one cannot be corrected. Unique removal gives such a protein a smaller set of batches that another protein has, when one exists, so it can be corrected with them, at the cost of its values in the batches it gives up. HarmonizR introduced the step ([Schlumbohm et al. 2025](References#schlumbohm-et-al-2025)). It is on by default (`unique_removal=True`, or `--no-unique-removal` to switch it off). + +## The rule + +For each feature whose affiliation is its own, HarmonizePy looks at the affiliations of the other features and picks the longest one that is a proper subset of the feature's affiliation. The feature takes that affiliation, joins its group, and its values in the dropped batches come out empty. + +- The target may be held by a single other feature. That feature then keeps its affiliation, and the two form a group. +- Features are taken longest affiliation first, and among equally long targets the one more features hold wins, then the smallest. The result does not depend on the order of the rows. +- An affiliation that spans a single batch is never a target: its group would be left raw, so the move would only empty the feature's other values. +- A feature with no target keeps its affiliation, and stays a group of one with its measured values. +- A feature with an empty affiliation is left alone; it comes out empty either way. + +## On the example + +In the [Quick start](Quick-Start) example, P4 is measured in batches 1, 2 and 3, and no other protein is. (1, 2), held by P1 to P3, is the longest affiliation inside (1, 2, 3), so P4 moves: + +```text +INFO [harmonizepy] Unique removal moved 1 feature(s) into a shared pattern (12.5%) +``` + +The log calls an affiliation a pattern. + +

+ + + + Three rows over batches 1 to 3: P1 to P3 measured in batches 1 and 2; P4 measured in all three, with batch 3 hatched as cut; P5 measured in batches 2 and 3, with no shared affiliation inside its pattern. + +

+

Figure 1. P4's affiliation (1, 2, 3) is its own, and (1, 2) is shared by three proteins and fits inside it, so P4 gives up batch 3 and joins them. P5's affiliation (2, 3) has only one-batch affiliations inside it, which are never targets, so P5 stays alone.

+ +| Run | P4 status | P4 in s7 to s9 | Group of P1 to P3 | +| ---------------------- | ---------------------- | ---------------- | ----------------- | +| default | `corrected`, cropped | empty | 4 features | +| `unique_removal=False` | `raw_alone_in_pattern` | 17.9, 18.6, 18.1 | 3 features | + +- With unique removal on, P4's batch 3 values are lost and its batches 1 and 2 are corrected. With it off, P4 keeps all nine values uncorrected. +- The choice also changes the other features of the group: P1's corrected value in `s1` is 20.67 with P4 in the group and 20.70 without it. + +P5, measured in batches 2 and 3, has only (2) and (3) inside its affiliation, and an affiliation of one batch is never a target. It stays alone and raw under both settings. + +The report marks a moved feature with `cropped` set to true, and its `batches_used` lists the batches it kept (see [Correction report](Correction-Report)). + +## Choosing the setting + +The setting is a trade between correcting more features and keeping more measured values: + +- On: a feature with an affiliation of its own, and another feature's affiliation of two or more batches inside it, is corrected over fewer batches, and its values in the cropped batches disappear from the output. +- Off: such a feature keeps its measured values in the batches of its affiliation, uncorrected, with its batch effect in place. + +Neither is right for every study. + +> [!TIP] +> The report shows what the choice costs: in a run with unique removal, the `cropped` rows are the features that gave up batches. Turning it off makes each of them `raw_alone_in_pattern`, next to the features it could not move. On the example that is 1 cropped feature (P4), and 2 `raw_alone_in_pattern` features without it (P4 and P5). + +## Difference from HarmonizR + +HarmonizR's `ur` option takes the same targets, with three differences: it walks the features in row order and takes the first of equally long targets, it empties the affiliation of a feature with no target, so that feature comes out empty, and it accepts a target of one batch. HarmonizePy's order makes the groups independent of the row order, and a feature with no target keeps its measured values (see [R compatibility](R-Compatibility)). + +## Related pages + +- [Pipeline](Pipeline): where unique removal sits between affiliations and groups. +- [Sorting and blocking](Sorting-and-Blocking): with blocking, affiliations are over blocks, and unique removal crops blocks instead of batches. diff --git a/wiki/_Footer.md b/wiki/_Footer.md index 518ccf5..5b1bdde 100644 --- a/wiki/_Footer.md +++ b/wiki/_Footer.md @@ -1 +1 @@ -*[[Home]] · [GitHub](https://github.com/LangeLab/HarmonizePy) · [Issues](https://github.com/LangeLab/HarmonizePy/issues) · v0.3.2 · GPL-3.0* +*[Home](Home) | [GitHub](https://github.com/LangeLab/HarmonizePy) | [Issues](https://github.com/LangeLab/HarmonizePy/issues) | GPL-3.0* diff --git a/wiki/_Sidebar.md b/wiki/_Sidebar.md index a068df8..b1a2776 100644 --- a/wiki/_Sidebar.md +++ b/wiki/_Sidebar.md @@ -1,27 +1,38 @@ **HarmonizePy** ---- - **Getting started** -* [[Home]] -* [[Installation]] -* [[Quick-Start]] ---- +- [Home](Home) +- [Installation](Installation) +- [Quick start](Quick-Start) -**User guide** -* [[Input-Format]] -* [[Algorithms]] -* [[Pipeline]] +**The data** ---- +- [Batch effects](Batch-Effects) +- [Missing values](Missing-Values) +- [Input format](Input-Format) -**Reference** -* [[API-Reference]] -* [[CLI-Reference]] +**The pipeline** + +- [Pipeline](Pipeline) +- [Unique removal](Unique-Removal) +- [Sorting and blocking](Sorting-and-Blocking) + +**The engines** ---- +- [Choosing an engine](Algorithms) +- [ComBat](ComBat) +- [limma](limma) + +**Results** + +- [Correction report](Correction-Report) +- [Limits](Limits) + +**Reference** -**Validation & performance** -* [[R-Compatibility]] -* [[Benchmarks]] +- [API reference](API-Reference) +- [CLI reference](CLI-Reference) +- [R compatibility](R-Compatibility) +- [Benchmarks](Benchmarks) +- [References](References) diff --git a/wiki/assets/batch-shift-dark.png b/wiki/assets/batch-shift-dark.png new file mode 100644 index 0000000..e32a404 Binary files /dev/null and b/wiki/assets/batch-shift-dark.png differ diff --git a/wiki/assets/batch-shift-light.png b/wiki/assets/batch-shift-light.png new file mode 100644 index 0000000..b875bd0 Binary files /dev/null and b/wiki/assets/batch-shift-light.png differ diff --git a/wiki/assets/benchmark-blocking-dark.png b/wiki/assets/benchmark-blocking-dark.png new file mode 100644 index 0000000..9032f0c Binary files /dev/null and b/wiki/assets/benchmark-blocking-dark.png differ diff --git a/wiki/assets/benchmark-blocking-light.png b/wiki/assets/benchmark-blocking-light.png new file mode 100644 index 0000000..0edcbdd Binary files /dev/null and b/wiki/assets/benchmark-blocking-light.png differ diff --git a/wiki/assets/benchmark-memory-dark.png b/wiki/assets/benchmark-memory-dark.png new file mode 100644 index 0000000..050ff06 Binary files /dev/null and b/wiki/assets/benchmark-memory-dark.png differ diff --git a/wiki/assets/benchmark-memory-light.png b/wiki/assets/benchmark-memory-light.png new file mode 100644 index 0000000..21b94bb Binary files /dev/null and b/wiki/assets/benchmark-memory-light.png differ diff --git a/wiki/assets/benchmark-memory-scaling-dark.png b/wiki/assets/benchmark-memory-scaling-dark.png new file mode 100644 index 0000000..682b724 Binary files /dev/null and b/wiki/assets/benchmark-memory-scaling-dark.png differ diff --git a/wiki/assets/benchmark-memory-scaling-light.png b/wiki/assets/benchmark-memory-scaling-light.png new file mode 100644 index 0000000..c666fa3 Binary files /dev/null and b/wiki/assets/benchmark-memory-scaling-light.png differ diff --git a/wiki/assets/benchmark-outcomes-dark.png b/wiki/assets/benchmark-outcomes-dark.png new file mode 100644 index 0000000..60d2197 Binary files /dev/null and b/wiki/assets/benchmark-outcomes-dark.png differ diff --git a/wiki/assets/benchmark-outcomes-light.png b/wiki/assets/benchmark-outcomes-light.png new file mode 100644 index 0000000..a37f8ad Binary files /dev/null and b/wiki/assets/benchmark-outcomes-light.png differ diff --git a/wiki/assets/benchmark-scaling-dark.png b/wiki/assets/benchmark-scaling-dark.png new file mode 100644 index 0000000..6627b57 Binary files /dev/null and b/wiki/assets/benchmark-scaling-dark.png differ diff --git a/wiki/assets/benchmark-scaling-light.png b/wiki/assets/benchmark-scaling-light.png new file mode 100644 index 0000000..5321663 Binary files /dev/null and b/wiki/assets/benchmark-scaling-light.png differ diff --git a/wiki/assets/benchmark-speed-dark.png b/wiki/assets/benchmark-speed-dark.png new file mode 100644 index 0000000..adb8f32 Binary files /dev/null and b/wiki/assets/benchmark-speed-dark.png differ diff --git a/wiki/assets/benchmark-speed-light.png b/wiki/assets/benchmark-speed-light.png new file mode 100644 index 0000000..3a8cf17 Binary files /dev/null and b/wiki/assets/benchmark-speed-light.png differ diff --git a/wiki/assets/blocking-dark.png b/wiki/assets/blocking-dark.png new file mode 100644 index 0000000..b09db3a Binary files /dev/null and b/wiki/assets/blocking-dark.png differ diff --git a/wiki/assets/blocking-light.png b/wiki/assets/blocking-light.png new file mode 100644 index 0000000..3b3b04f Binary files /dev/null and b/wiki/assets/blocking-light.png differ diff --git a/wiki/assets/combat-modes-dark.png b/wiki/assets/combat-modes-dark.png new file mode 100644 index 0000000..8bd9f55 Binary files /dev/null and b/wiki/assets/combat-modes-dark.png differ diff --git a/wiki/assets/combat-modes-light.png b/wiki/assets/combat-modes-light.png new file mode 100644 index 0000000..440017c Binary files /dev/null and b/wiki/assets/combat-modes-light.png differ diff --git a/wiki/assets/input-anatomy-dark.png b/wiki/assets/input-anatomy-dark.png new file mode 100644 index 0000000..312b0b7 Binary files /dev/null and b/wiki/assets/input-anatomy-dark.png differ diff --git a/wiki/assets/input-anatomy-light.png b/wiki/assets/input-anatomy-light.png new file mode 100644 index 0000000..53c89da Binary files /dev/null and b/wiki/assets/input-anatomy-light.png differ diff --git a/wiki/assets/levels-dark.png b/wiki/assets/levels-dark.png new file mode 100644 index 0000000..df67f1b Binary files /dev/null and b/wiki/assets/levels-dark.png differ diff --git a/wiki/assets/levels-light.png b/wiki/assets/levels-light.png new file mode 100644 index 0000000..5214515 Binary files /dev/null and b/wiki/assets/levels-light.png differ diff --git a/wiki/assets/location-scale-dark.png b/wiki/assets/location-scale-dark.png new file mode 100644 index 0000000..a255d64 Binary files /dev/null and b/wiki/assets/location-scale-dark.png differ diff --git a/wiki/assets/location-scale-light.png b/wiki/assets/location-scale-light.png new file mode 100644 index 0000000..6b31d7a Binary files /dev/null and b/wiki/assets/location-scale-light.png differ diff --git a/wiki/assets/missing-matrix-dark.png b/wiki/assets/missing-matrix-dark.png new file mode 100644 index 0000000..dd1fece Binary files /dev/null and b/wiki/assets/missing-matrix-dark.png differ diff --git a/wiki/assets/missing-matrix-light.png b/wiki/assets/missing-matrix-light.png new file mode 100644 index 0000000..52550be Binary files /dev/null and b/wiki/assets/missing-matrix-light.png differ diff --git a/wiki/assets/pipeline-groups-dark.png b/wiki/assets/pipeline-groups-dark.png new file mode 100644 index 0000000..74cc0a8 Binary files /dev/null and b/wiki/assets/pipeline-groups-dark.png differ diff --git a/wiki/assets/pipeline-groups-light.png b/wiki/assets/pipeline-groups-light.png new file mode 100644 index 0000000..c5f18df Binary files /dev/null and b/wiki/assets/pipeline-groups-light.png differ diff --git a/wiki/assets/shrinkage-dark.png b/wiki/assets/shrinkage-dark.png new file mode 100644 index 0000000..47fe0fe Binary files /dev/null and b/wiki/assets/shrinkage-dark.png differ diff --git a/wiki/assets/shrinkage-light.png b/wiki/assets/shrinkage-light.png new file mode 100644 index 0000000..3c7a0fb Binary files /dev/null and b/wiki/assets/shrinkage-light.png differ diff --git a/wiki/assets/unique-removal-dark.png b/wiki/assets/unique-removal-dark.png new file mode 100644 index 0000000..907d201 Binary files /dev/null and b/wiki/assets/unique-removal-dark.png differ diff --git a/wiki/assets/unique-removal-light.png b/wiki/assets/unique-removal-light.png new file mode 100644 index 0000000..d6391c5 Binary files /dev/null and b/wiki/assets/unique-removal-light.png differ diff --git a/wiki/limma.md b/wiki/limma.md new file mode 100644 index 0000000..05a9841 --- /dev/null +++ b/wiki/limma.md @@ -0,0 +1,60 @@ +# limma + +limma's `removeBatchEffect` (in the `limma` package, [Ritchie et al. 2015](References#ritchie-et-al-2015)) fits each feature on its own: a linear model with an intercept and one sum-to-zero column per batch, solved by least squares, with the fitted batch part then subtracted and the intercept kept. There is no prior and no borrowing between features, and the spread of a batch is never changed. HarmonizePy's `remove_batch_effect()` is a NumPy version of it, and `algorithm="limma"` runs it on every affiliation group. + +## The model + +For feature $`g`$ in sample $`j`$, with $`I`$ batches: + +```math +y_{gj} = \beta_{g0} + \sum_{k=1}^{I-1} \beta_{gk}\, x_{jk} + \varepsilon_{gj} +``` + +The batch columns $`x_{jk}`$ are sum-to-zero contrasts, as R's `contr.sum` builds them: 1 for samples of batch $`k`$, -1 for samples of the last batch, 0 otherwise. The correction subtracts the fitted batch part and keeps the intercept: + +```math +\tilde y_{gj} = y_{gj} - \sum_{k=1}^{I-1} \hat\beta_{gk}\, x_{jk} +``` + +With these contrasts the intercept is the unweighted mean of the batch means, so after correction every batch mean of the feature equals that value, whatever the batch sizes. ComBat's level is weighted by batch size instead (see [ComBat](ComBat#the-model)), so the two engines place a feature at different levels when batches differ in size. + +

+ + + + One feature with batches of 6, 6 and 2 samples: its input batch means differ; after ComBat the three batch means sit near the size-weighted mean, and after limma exactly at the unweighted mean. + +

+

Figure 1. One feature of a simulated ten-feature matrix, in batches of 6, 6 and 2 samples. After correction its batch means meet at the dashed line: for ComBat near the mean weighted by batch size, so the small batch counts less, and for limma exactly at the plain mean of the three batch means.

+ +## On the example + +Batch means of two proteins from the [Quick start](Quick-Start) example, over batches 1 and 2 (their group): + +```text + input limma ComBat mode 1 + batch 1 batch 2 batch 1 batch 2 batch 1 batch 2 +P1 19.85 21.33 20.59 20.59 20.45 20.72 +P2 18.27 19.77 19.02 19.02 19.08 18.95 +``` + +limma puts both batch means exactly at their average: P2 at 19.02, halfway between 18.27 and 19.77. ComBat does not set the means equal: it estimates each protein's shift partly from the other proteins of the group, and P2 ends with batch 1 at 19.08 and batch 2 at 18.95. + +## Missing cells + +Features with the same pattern of observed cells are fitted together, on the samples they have. Gaps stay gaps in the output. Inside `harmonize()` every feature has values in every batch of its group, so the full set of batch terms is always estimable. + +Called directly, `remove_batch_effect()` also handles a feature missing a whole batch, by fitting contrasts over the batches it has. It keeps a feature raw when it has values in one batch only, or when it has no more values than batches it is observed in, since the fit would leave nothing but the batch means. One difference from `limma::removeBatchEffect` follows: for a feature missing its first or last batch, R sets the coefficient it cannot estimate to zero and corrects the other batches with the coefficients that remain, while HarmonizePy refits the contrasts over the batches the feature has and moves them to their common mean, so the two give different values (see [R compatibility](R-Compatibility)). + +## Edges worth knowing + +- A batch with one sample. limma has no minimum batch size. That sample's batch term absorbs its whole deviation, so its corrected value is the intercept for every feature, and its own signal is removed. ComBat handles the same case by switching to location-only correction. Inside `harmonize()` a one-sample batch counts only with `needed_values=1`; with the default of 2 its sample comes out empty. +- One value per batch. A feature with no more values than batches it is observed in, such as one value in each batch, would be collapsed to one number; it keeps its measured values instead and is reported `raw_too_few_values`. With `needed_values` at its default of 2 for limma, this arises only when `needed_values=1` is set by hand. +- A single feature passed directly to `remove_batch_effect()` is corrected. Inside `harmonize()` a group of one feature is left raw. +- No covariates. HarmonizePy's version takes the batch labels only; there is no `design`, `covariates` or `batch2` argument as in R. + +## Related pages + +- [Choosing an engine](Algorithms): limma against ComBat. +- [R compatibility](R-Compatibility): the tolerances against `limma::removeBatchEffect`. +- [API reference](API-Reference#remove_batch_effect): the `remove_batch_effect()` and `adjust_limma()` signatures.