diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..af90966 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +# Only the package source goes into the image (see Dockerfile) +.git +.github +.idea +**/__pycache__ +**/*.pyc +*.egg-info +build +dist +docs +tests +packaging +test_data +e2e_out +maxatac/git_version +.Rhistory diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..b2d8e4b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,80 @@ +name: CI + +# Fast checks on every push and pull request: install, CLI smoke test, lint for errors, unit tests. +# The data -> predict -> benchmark run lives in e2e.yml. + +on: + push: + # Branches only: release tags run this through release.yml + branches: ["**"] + pull_request: + workflow_dispatch: + workflow_call: + +permissions: + contents: read + +concurrency: + # github.workflow is the caller's name when called from release.yml, so a release never cancels a branch run + group: ${{ github.workflow }}-ci-${{ github.ref }} + cancel-in-progress: true + +env: + TF_CPP_MIN_LOG_LEVEL: "2" + CUDA_VISIBLE_DEVICES: "" + +jobs: + test: + name: Unit tests (Python ${{ matrix.python-version }}) + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + # setup.py pins tensorflow>=2.14,<2.16, which has wheels for Python 3.9-3.11 + python-version: ["3.10", "3.11"] + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + cache: pip + cache-dependency-path: setup.py + + - name: Install system dependencies + # pybedtools calls the bedtools binary + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends bedtools + + - name: Install ushuffle + # The PyPI release of ushuffle (a quant-maxATAC dependency) does not build; install it from source first. + # --no-build-isolation needs the build tools already installed. If the build fails, retry with Cython < 3. + run: | + # setuptools 82 removed pkg_resources, which older dependencies (e.g. TF 2.15-era tensorboard) still import + python -m pip install --upgrade pip "setuptools<82" wheel + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git || { + echo "::warning::ushuffle build failed; retrying with Cython < 3" + pip install "cython<3" + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git + } + python -c "from ushuffle import shuffle; print(shuffle(b'ACGTACGTAC', 2))" + + - name: Install quant-maxATAC + run: | + pip install -e . pytest flake8 + + - name: CLI smoke test + run: | + maxatac -h + for command in data predict benchmark threshold train; do + maxatac "$command" -h > /dev/null + done + + - name: Lint (errors only) + # Syntax errors and undefined names; style is not enforced + run: flake8 maxatac tests --count --select=E9,F63,F7,F82 --show-source --statistics + + - name: Unit tests + # data -> predict -> benchmark on real data is covered by e2e.yml + run: pytest -v tests --ignore=tests/e2e diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml new file mode 100644 index 0000000..b826527 --- /dev/null +++ b/.github/workflows/e2e.yml @@ -0,0 +1,143 @@ +name: End-to-end + +# The user path on real data: `maxatac data` -> `maxatac predict` -> `maxatac benchmark` +# inputs: https://github.com/XiaotingChen/quant-maxATAC_test_data (Git LFS) +# models: https://github.com/MiraldiLab/quant-maxATAC_data (installed by `maxatac data`) +# The steps themselves are in tests/e2e/run_e2e.sh so they can be run outside GitHub too. + +on: + push: + branches: [main, "quant*"] + pull_request: + workflow_dispatch: + inputs: + data_version: + description: "Data repository tag or branch (`maxatac data --data_version`); empty = match the code version" + required: false + default: "" + workflow_call: + # release.yml passes the release tag, so a release is tested with the data of the same tag + inputs: + data_version: + type: string + required: false + default: "" + schedule: + # Weekly, to catch changes in the data repositories and in unpinned dependencies + - cron: "0 6 * * 1" + +permissions: + contents: read + +concurrency: + # github.workflow is the caller's name when called from release.yml, so a release never cancels a branch run + group: ${{ github.workflow }}-e2e-${{ github.ref }} + cancel-in-progress: true + +env: + TEST_DATA_REPO: XiaotingChen/quant-maxATAC_test_data + DATA_VERSION: ${{ inputs.data_version }} + TF_CPP_MIN_LOG_LEVEL: "2" + CUDA_VISIBLE_DEVICES: "" + +jobs: + e2e: + name: data -> predict -> benchmark (GM12878 CTCF, chr1 slice) + runs-on: ubuntu-latest + timeout-minutes: 60 + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + cache: pip + cache-dependency-path: setup.py + + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends bedtools wget + + - name: Install ushuffle + # The PyPI release of ushuffle (a quant-maxATAC dependency) does not build; install it from source first. + # --no-build-isolation needs the build tools already installed. If the build fails, retry with Cython < 3. + run: | + # setuptools 82 removed pkg_resources, which older dependencies (e.g. TF 2.15-era tensorboard) still import + python -m pip install --upgrade pip "setuptools<82" wheel + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git || { + echo "::warning::ushuffle build failed; retrying with Cython < 3" + pip install "cython<3" + pip install --no-build-isolation git+https://github.com/guma44/ushuffle.git + } + python -c "from ushuffle import shuffle; print(shuffle(b'ACGTACGTAC', 2))" + + - name: Install quant-maxATAC + run: | + pip install -e . + + # ---- Test inputs: Git LFS files, cached per commit of the test data repository so each + # commit is downloaded once (LFS bandwidth is metered on the repository owner's account) + - name: Resolve test data commit + id: test-data + run: echo "sha=$(git ls-remote "https://github.com/${TEST_DATA_REPO}.git" HEAD | cut -f1)" >> "$GITHUB_OUTPUT" + + - name: Restore test data + id: test-data-cache + uses: actions/cache/restore@v4 + with: + path: test_data/data + key: test-data-${{ steps.test-data.outputs.sha }} + + - name: Download test data + if: steps.test-data-cache.outputs.cache-hit != 'true' + uses: actions/checkout@v4 + with: + repository: ${{ env.TEST_DATA_REPO }} + ref: ${{ steps.test-data.outputs.sha }} + path: test_data + lfs: true + + - name: Save test data + if: steps.test-data-cache.outputs.cache-hit != 'true' + uses: actions/cache/save@v4 + with: + path: test_data/data + key: test-data-${{ steps.test-data.outputs.sha }} + + # ---- hg38.2bit (~800 MB from UCSC). Restored into the data directory before `maxatac data`, + # which carries an existing .2bit over into the fresh clone instead of downloading it again + - name: Restore hg38.2bit + id: twobit-cache + uses: actions/cache/restore@v4 + with: + path: ~/opt/maxatac/data/hg38/hg38.2bit + key: hg38-2bit-v1 + + - name: Run data -> predict -> benchmark + run: bash tests/e2e/run_e2e.sh + env: + TEST_DATA: test_data/data + OUT: e2e_out + + - name: Check for a downloaded hg38.2bit + id: twobit + if: always() && steps.twobit-cache.outputs.cache-hit != 'true' + # hashFiles() only sees the workspace, so test for the file directly + run: | + if [ -s ~/opt/maxatac/data/hg38/hg38.2bit ]; then echo "present=true" >> "$GITHUB_OUTPUT"; fi + + - name: Save hg38.2bit + if: always() && steps.twobit.outputs.present == 'true' + uses: actions/cache/save@v4 + with: + path: ~/opt/maxatac/data/hg38/hg38.2bit + key: hg38-2bit-v1 + + - name: Upload outputs + if: always() + uses: actions/upload-artifact@v4 + with: + name: e2e-outputs + path: e2e_out + retention-days: 14 + if-no-files-found: ignore diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..13bae27 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,187 @@ +name: Release + +# Push a version tag to release, e.g. +# git tag -a v2.0.0b2 -m "q-maxATAC v2 preview 2" && git push xc v2.0.0b2 +# +# 1. Runs CI and the end-to-end test on the tagged commit, the latter with the data repository tag of the same +# name (`maxatac data --data_version `): tag MiraldiLab/quant-maxATAC_data first, or the release fails +# 2. Builds the sdist and wheel and checks their version matches the tag +# 3. Once CI and the end-to-end test pass, builds the Docker image from the tagged commit, checks the version +# inside it and pushes it to ghcr.io//quant-maxatac: (and :latest for final releases) +# 4. Creates a GitHub Release with the packages, the e2e metrics and the image in the notes and the benchmark +# files attached. a/b/rc tags (v2.0.0b2, v2.0.0rc1) are marked as pre-releases +# +# The first image pushed to a repository owner's GHCR is private: make it public once in the package settings. +# +# Tags must be PEP 440 versions with a leading "v": v2.0.0, v2.0.0b1, v2.0.0rc1. Never move or reuse a tag. + +on: + push: + tags: ["v*"] + +permissions: + contents: read + +jobs: + ci: + uses: ./.github/workflows/ci.yml + + e2e: + uses: ./.github/workflows/e2e.yml + with: + data_version: ${{ github.ref_name }} + + build: + name: Build packages + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + # Full history and tags: setup.py reads the version from the tag on this commit + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Build sdist and wheel + run: | + python -m pip install --upgrade pip build twine + python -m build + twine check dist/* + + - name: Check the version matches the tag + # Catches tags that are not PEP 440 versions (e.g. v2.0.0-preview.1 would be built as 2.0.0rc1) + run: | + version="${GITHUB_REF_NAME#v}" + ls dist + if [ ! -f "dist/maxatac-${version}.tar.gz" ]; then + echo "::error::Built packages do not have version ${version} from tag ${GITHUB_REF_NAME}" + exit 1 + fi + + - uses: actions/upload-artifact@v4 + with: + name: dist + path: dist + retention-days: 14 + + image: + name: Docker image + # Only publish an image of code that passed the checks + needs: [ci, e2e] + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + outputs: + image: ${{ steps.name.outputs.image }} + steps: + - uses: actions/checkout@v4 + + - name: Image name and version + id: name + # GHCR names must be lowercase; the owner follows the repository, so this works unchanged upstream + run: | + version="${GITHUB_REF_NAME#v}" + echo "version=${version}" >> "$GITHUB_OUTPUT" + echo "repo=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/quant-maxatac" >> "$GITHUB_OUTPUT" + echo "image=ghcr.io/${GITHUB_REPOSITORY_OWNER,,}/quant-maxatac:${version}" >> "$GITHUB_OUTPUT" + + - uses: docker/setup-buildx-action@v3 + + - uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + + - name: Build + uses: docker/build-push-action@v6 + with: + context: . + # The image has no .git: the version comes from the tag of the commit it is built from + build-args: | + MAXATAC_VERSION=${{ steps.name.outputs.version }} + SOURCE_URL=${{ github.server_url }}/${{ github.repository }} + load: true + tags: ${{ steps.name.outputs.image }} + cache-from: type=gha + cache-to: type=gha,mode=max + + - name: Test the image + env: + IMAGE: ${{ steps.name.outputs.image }} + VERSION: ${{ steps.name.outputs.version }} + run: | + docker run --rm "${IMAGE}" maxatac -h > /dev/null + installed=$(docker run --rm "${IMAGE}" python -c "from importlib import metadata; print(metadata.version('maxatac'))") + if [ "${installed}" != "${VERSION}" ]; then + echo "::error::The image has maxatac ${installed}, expected ${VERSION}" + exit 1 + fi + docker run --rm "${IMAGE}" python -c "from ushuffle import shuffle; shuffle(b'ACGTACGTAC', 2)" + docker images "${IMAGE}" + + - name: Push + env: + IMAGE: ${{ steps.name.outputs.image }} + REPO: ${{ steps.name.outputs.repo }} + run: | + docker push "${IMAGE}" + # :latest only moves to final releases, never to a/b/rc pre-releases + if [[ ! "${GITHUB_REF_NAME}" =~ (a|b|rc)[0-9]+$ ]]; then + docker tag "${IMAGE}" "${REPO}:latest" + docker push "${REPO}:latest" + fi + + release: + name: GitHub Release + needs: [ci, e2e, build, image] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/download-artifact@v4 + with: + name: dist + path: dist + + - uses: actions/download-artifact@v4 + with: + name: e2e-outputs + path: e2e_out + + - name: Write release notes + env: + IMAGE: ${{ needs.image.outputs.image }} + run: | + { + echo "quant-maxATAC ${GITHUB_REF_NAME}, tested with [quant-maxATAC_data ${GITHUB_REF_NAME}](https://github.com/MiraldiLab/quant-maxATAC_data/tree/${GITHUB_REF_NAME})." + echo + echo "Install: \`pip install https://github.com/${GITHUB_REPOSITORY}/releases/download/${GITHUB_REF_NAME}/$(cd dist && ls *.whl)\`, then \`maxatac data\` installs the matching models." + echo + echo "Docker: \`docker pull ${IMAGE}\` (no data inside: mount ~/opt/maxatac, see the [Dockerfile](https://github.com/${GITHUB_REPOSITORY}/blob/${GITHUB_REF_NAME}/Dockerfile))." + echo + cat e2e_out/metrics.md + } > notes.md + cat notes.md + + - name: Create the release + env: + GH_TOKEN: ${{ github.token }} + run: | + shopt -s nullglob + prerelease="" + if [[ "${GITHUB_REF_NAME}" =~ (a|b|rc)[0-9]+$ ]]; then prerelease="--prerelease"; fi + + gh release create "${GITHUB_REF_NAME}" \ + --repo "${GITHUB_REPOSITORY}" \ + --title "quant-maxATAC ${GITHUB_REF_NAME}" \ + --notes-file notes.md \ + --generate-notes \ + ${prerelease} \ + dist/* \ + e2e_out/metrics.json \ + e2e_out/benchmark/*.tsv \ + e2e_out/benchmark/*.png diff --git a/.gitignore b/.gitignore index 8f90e03..7cf290e 100644 --- a/.gitignore +++ b/.gitignore @@ -115,3 +115,7 @@ snakemake/dag.svg # Readme Swp file *.INSTALL.md.swp + +# End-to-end test (tests/e2e/run_e2e.sh) +test_data/ +e2e_out/ diff --git a/Dockerfile b/Dockerfile index 410625f..0219bf8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,70 +1,88 @@ ################################################################# -# Dockerfile +# quant-maxATAC (CPU) # -# Software: maxATAC -# Software Version: v0.0.3 -# Description: python based suite for transcription factor binding prediction -# Website: https://github.com/MiraldiLab/maxATAC -# Website2: https://github.com/MiraldiLab/maxATAC_data -# Provides: Transcription Factor Binding Prediction -# Base Image: biowardrobe2/samtools:v1.4/bedtools/ucsc-bedgraphtobigwig/pigz -# Build Cmd: docker build --rm -t miraldi/maxatac:v0.0.3 -f Dockerfile . -# Pull Cmd: docker pull miraldi/maxatac:v0.0.3 -# Run Cmd: docker run --rm -ti miraldi/maxatac:v0.0.3 +# Build: docker build -t quant-maxatac --build-arg MAXATAC_VERSION=2.0.0b2 . +# MAXATAC_VERSION is the release without its "v" (the git tag is not copied into the image). It decides +# which data tag `maxatac data` installs; without it the image is a development version and installs the +# latest data. +# +# The image holds no reference data or models (the hg38.2bit alone is ~800 MB). Keep them on the host under +# ~/opt/maxatac and mount that directory; `maxatac data` fills it once and later runs reuse it: +# +# docker run --rm --user "$(id -u):$(id -g)" -v ~/opt/maxatac:/home/maxatac/opt/maxatac \ +# quant-maxatac maxatac data +# docker run --rm --user "$(id -u):$(id -g)" -v ~/opt/maxatac:/home/maxatac/opt/maxatac -v "$PWD":/work \ +# quant-maxatac maxatac predict --tf_name CTCF --signal sample.bw --prefix sample_CTCF +# +# Singularity/Apptainer mounts your home directory by default, so ~/opt/maxatac/data on the host is used as is: +# apptainer exec docker:// maxatac predict ... ################################################################# +ARG PYTHON_VERSION=3.11 -# Dockerfile, Image, Container +########## Build stage: compile the Python packages into a virtualenv ########## +FROM python:${PYTHON_VERSION}-slim-bookworm AS build -FROM python:3.9 +# Compilers and headers for packages without wheels (ushuffle, py2bit, ...) +RUN apt-get update && \ + apt-get install -y --no-install-recommends build-essential git zlib1g-dev libbz2-dev liblzma-dev \ + libcurl4-openssl-dev && \ + rm -rf /var/lib/apt/lists/* -################## BEGIN INSTALLATION ###################### +RUN python -m venv /opt/venv +ENV PATH=/opt/venv/bin:$PATH -WORKDIR /tmp +# setuptools 82 removed pkg_resources, which older dependencies (e.g. TF 2.15-era tensorboard) still import +RUN pip install --no-cache-dir --upgrade pip "setuptools<82" wheel -ENV VERSION_BEDTOOLS 2.26.0 -ENV URL_BEDTOOLS "https://github.com/arq5x/bedtools2/releases/download/v${VERSION_BEDTOOLS}/bedtools-${VERSION_BEDTOOLS}.tar.gz" +# The PyPI release of ushuffle does not build: install it from source first, as in .github/workflows/ci.yml. +# --no-build-isolation needs the build tools above. If the build fails, retry with Cython < 3 +ARG USHUFFLE_SOURCE=git+https://github.com/guma44/ushuffle.git@b54df34f60246ff236ec58bbccb40af3cea608ed +RUN (pip install --no-cache-dir --no-build-isolation "${USHUFFLE_SOURCE}" || \ + (pip install --no-cache-dir "cython<3" && pip install --no-cache-dir --no-build-isolation "${USHUFFLE_SOURCE}")) && \ + python -c "from ushuffle import shuffle; shuffle(b'ACGTACGTAC', 2)" -ENV VERSION_HTSLIB 1.12 -ENV URL_HTSLIB "https://github.com/samtools/htslib/releases/download/${VERSION_HTSLIB}/htslib-${VERSION_HTSLIB}.tar.bz2" +COPY . /src -ENV VERSION_SAMTOOLS 1.12 -ENV URL_SAMTOOLS "https://github.com/samtools/samtools/releases/download/${VERSION_SAMTOOLS}/samtools-${VERSION_SAMTOOLS}.tar.bz2" +# Without .git, setup.py reads the version from maxatac/git_version +ARG MAXATAC_VERSION="" +RUN if [ -n "${MAXATAC_VERSION}" ]; then printf "%s" "${MAXATAC_VERSION#v}" > /src/maxatac/git_version; fi && \ + pip install --no-cache-dir /src -ENV URL_UCSC "http://hgdownload.soe.ucsc.edu/admin/exe/userApps.src.tgz" +########## Runtime stage ########## +FROM python:${PYTHON_VERSION}-slim-bookworm +ARG MAXATAC_VERSION="" +# GHCR links the image to this repository (release.yml passes the repository that built it) +ARG SOURCE_URL=https://github.com/MiraldiLab/quant-maxATAC +LABEL org.opencontainers.image.title="quant-maxATAC" \ + org.opencontainers.image.description="Deep neural networks predicting quantitative TF ChIP-seq signal from ATAC-seq signal and DNA sequence" \ + org.opencontainers.image.source="${SOURCE_URL}" \ + org.opencontainers.image.version="${MAXATAC_VERSION}" \ + org.opencontainers.image.licenses="Apache-2.0" +# git, wget: `maxatac data`. samtools, bedtools, pigz, bedGraphToBigWig: `maxatac prepare`; bedtools also for +# pybedtools in predict/benchmark +ARG BEDGRAPHTOBIGWIG_URL=https://hgdownload.soe.ucsc.edu/admin/exe/linux.x86_64/bedGraphToBigWig RUN apt-get update && \ - apt-get install -y gcc-10-base libgcc-10-dev libxml2-dev libcurl4-openssl-dev libssl-dev pandoc libgtextutils-dev libmariadb-dev-compat libmariadb-dev libpng-dev uuid-dev libncurses5-dev libbz2-dev liblzma-dev pigz rsync && \ -### Install htslib - wget -q -O - $URL_HTSLIB | tar -jxv && \ - cd htslib-${VERSION_HTSLIB} && \ - ./configure --prefix=/usr/local/ && \ - make -j 4 && \ - make install && \ - cd .. && \ -### Install samtools - wget -q -O - $URL_SAMTOOLS | tar -jxv && \ - cd samtools-${VERSION_SAMTOOLS} && \ - ./configure --prefix=/usr/local/ && \ - make -j 4 && \ - make install && \ - cd .. && \ -### Install bedtools - wget -q -O - $URL_BEDTOOLS | tar -zxv && \ - cd bedtools2 && \ - make -j 4 && \ - cd .. && \ - cp ./bedtools2/bin/bedtools /usr/local/bin/ && \ -### Install UCSC User Apps - wget -q -O - $URL_UCSC | tar -zxv --strip-components=2 && \ - make -j 2 && \ - cp ./bin/* /usr/local/bin/ &&\ - rm -rf ./* &&\ - pip install maxatac==0.0.3 &&\ - mkdir -p /opt/maxatac && cd /opt/maxatac &&\ - git clone https://github.com/MiraldiLab/maxATAC_data.git && mv maxATAC_data data &&\ - cd ./data/hg38 && wget https://hgdownload.cse.ucsc.edu/goldenpath/hg38/bigZips/hg38.2bit &&\ - strip /usr/local/bin/*; true - -CMD ["maxatac"] + apt-get install -y --no-install-recommends bedtools samtools pigz git wget ca-certificates && \ + rm -rf /var/lib/apt/lists/* && \ + wget -q -O /usr/local/bin/bedGraphToBigWig "${BEDGRAPHTOBIGWIG_URL}" && \ + chmod +x /usr/local/bin/bedGraphToBigWig && \ + (bedGraphToBigWig 2>&1 || true) | grep -q "usage" + +COPY --from=build /opt/venv /opt/venv + +# A fixed HOME, so the data directory (~/opt/maxatac/data) is the same for any --user. World-writable because +# --user runs as an arbitrary uid +ENV PATH=/opt/venv/bin:$PATH \ + HOME=/home/maxatac \ + MPLCONFIGDIR=/tmp/matplotlib \ + TF_CPP_MIN_LOG_LEVEL=2 +RUN mkdir -p /home/maxatac/opt/maxatac /work && chmod -R 777 /home/maxatac /work + +WORKDIR /work + +RUN maxatac -h > /dev/null + +CMD ["maxatac", "-h"] diff --git a/INSTALL.md b/INSTALL.md index 652ba92..a26a0cb 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -5,21 +5,25 @@ below with the PyPI package name/version once quant-maxATAC is published. The do ## Install Instructions -### 1. To install maxATAC begin by downloading the data reopository located on github: maxATAC_data +The reference data and models are installed with `maxatac data` once quant-maxATAC is installed (step 4). To install them by hand instead, follow steps 1-3. - `git clone https://github.com/MiraldiLab/maxATAC_data.git` +### 1. Download the data repository located on github: [quant-maxATAC_data](https://github.com/MiraldiLab/quant-maxATAC_data) -### 2. To ensure that the data is located in a central location copy maxATAC_data to local location: +This replaces the maxATAC v1 [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository, whose binary models quant-maxATAC does not use. If you have an existing `~/opt/maxatac/data`, move it out of the way first. + +### 2. Clone it into the location quant-maxATAC looks in by default: ```bash -mkdir -p /opt/maxatac/data/ -cp -r ./maxATAC_data /opt/maxatac/ +mkdir -p ~/opt/maxatac +git clone --depth 1 https://github.com/MiraldiLab/quant-maxATAC_data.git ~/opt/maxatac/data ``` -### 3. Then Download hg38.2bit file from UCSC in a location of your choice +To match a quant-maxATAC release, clone the data tag of the same name, e.g. `git clone --depth 1 --branch v2.0.0b1 ...`. `maxatac data` does this for you. + +### 3. Then download the hg38.2bit file from UCSC next to the hg38 reference files ```bash -wget https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit +wget https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit -O ~/opt/maxatac/data/hg38/hg38.2bit ``` ### 4. Installing maxATAC diff --git a/README.md b/README.md index db0014d..8e82d0e 100644 --- a/README.md +++ b/README.md @@ -73,10 +73,9 @@ In order to run the distributed TF models, the following files are required and * TF specific threshold calibration tables (`_cross_celltype.tsv`, generated by [`maxatac threshold`](./docs/readme/threshold.md)) * Bash scripts for preparing data -The `maxatac data` function downloads the data repository and reference data into your `~/opt/` directory under `~/opt/maxatac`. Only the hg38 reference genome has been extensively tested. +The `maxatac data` function downloads the [quant-maxATAC_data](https://github.com/MiraldiLab/quant-maxATAC_data) repository and reference data into your `~/opt/` directory under `~/opt/maxatac`. Only the hg38 reference genome has been extensively tested. - +If `~/opt/maxatac/data` already exists, for example from a maxATAC v1 install, `maxatac data` asks before overwriting it, because the maxATAC v1 (binary) models in it will be replaced. If you are still interested in using the v1 models with quant-maxATAC, let us know on the [issue tracker](https://github.com/MiraldiLab/quant-maxATAC/issues). See [Data](./docs/readme/data.md) for details. #### Using custom reference data diff --git a/docs/readme/average.md b/docs/readme/average.md index 0307865..591dd47 100644 --- a/docs/readme/average.md +++ b/docs/readme/average.md @@ -58,6 +58,10 @@ The chromosomes that are averaged together and written to output. Only the chrom chr1 chr2 chr3 chr4 chr5 chr6 chr7 chr8 chr9 chr10 chr11 chr12 chr13 chr14 chr15 chr16 chr17 chr18 chr19 chr20 chr21 chr22 ``` +### `--max_zooms` + +The number of zoom levels to compute for the averaged bigWig file. Zoom levels are pre-computed summary statistics that let genome browsers (IGV, UCSC Genome Browser) zoom in and out of a region quickly; fewer levels mean slower loading in browsers, more levels mean more memory during writing. Valid range: `0`-`10`. Default: `10`. Note: a value of `0` produces a bigWig that is not compatible with other bigWig tools (e.g. deepTools) and cannot be visualized in IGV or the UCSC Genome Browser. See the [pyBigWig README](https://github.com/deeptools/pyBigWig/blob/master/README.md) for details. + ### `-o`, `--output`, `--output_dir` The output directory. If the output directory is not supplied the file will be created in the current working directory. diff --git a/docs/readme/data.md b/docs/readme/data.md index 1e13a60..0e44cd8 100644 --- a/docs/readme/data.md +++ b/docs/readme/data.md @@ -2,19 +2,29 @@ The `data` function downloads the reference data and models that the other functions look for by default under `~/opt/maxatac/data`: -* the [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository (blacklists, chromosome sizes, TF models with their `*_cross_celltype.tsv` threshold calibration tables, and the `prepare` shell scripts), cloned into `~/opt/maxatac/data` +* the [quant-maxATAC_data](https://github.com/MiraldiLab/quant-maxATAC_data) repository (blacklists, chromosome sizes, quant-maxATAC TF models with their `*_cross_celltype.tsv` threshold calibration tables, and the `prepare` shell scripts), cloned into `~/opt/maxatac/data` * the UCSC `.2bit` genome sequence for each requested genome, downloaded into `~/opt/maxatac/data//` - - `git` and `wget` must be on your PATH. +## Overwriting existing data and maxATAC v1 models + +quant-maxATAC uses its own data repository instead of the maxATAC v1 [maxATAC_data](https://github.com/MiraldiLab/maxATAC_data) repository. If `~/opt/maxatac/data` already exists, `maxatac data` lists what is installed there (the source repository and how many models look like v1 binary models) and asks for confirmation before replacing it. The whole directory is replaced, **including any maxATAC v1 models**. Answer anything other than `y` to leave it untouched. + +* The new data is cloned into a temporary directory first; the old directory is only removed once the clone has succeeded. +* `.2bit` files already present are kept, so they are not downloaded again. +* Without a terminal to answer the prompt (e.g. in a script or Docker build), `maxatac data` stops with an error unless `--yes` is given. + +If you are still interested in using the maxATAC v1 models with quant-maxATAC, let us know on the [issue tracker](https://github.com/MiraldiLab/quant-maxATAC/issues). + ## Example ```bash maxatac data maxatac data --genome hg38 hg19 +maxatac data --yes +maxatac data --data_version v2.0.0b1 +maxatac data --data_version latest ``` ## Optional Arguments @@ -27,6 +37,20 @@ One or more genome builds to download the `.2bit` sequence for, or `all` for `hg Base directory to install into; data is placed in `/maxatac/data`. Default: `~/opt` +### `--data_repo` + +Git repository to install the reference data and models from, e.g. a fork or mirror of quant-maxATAC_data. Default: `https://github.com/MiraldiLab/quant-maxATAC_data.git` + +### `--data_version` + +Tag or branch of the data repository to install, e.g. `v2.0.0b1`, or `latest` for the newest commit on its default branch. Default: the data tag matching the installed quant-maxATAC version (`maxatac --version`), so code and models from the same release are used together. Development installs (versions ending in `.dev0`) and versions without a matching tag install the latest data, with a warning. + +Releases are tagged with the same name in both repositories, following [PEP 440](https://peps.python.org/pep-0440/): `v2.0.0b1`, `v2.0.0b2`, … for previews, `v2.0.0rc1` for release candidates and `v2.0.0` for the release. + +### `-y`, `--yes` + +Overwrite an existing data directory, including any maxATAC v1 models, without asking for confirmation. + ### `--loglevel` Logging level (`fatal`, `error`, `warning`, `info`, `debug`). Default: `info`. diff --git a/docs/readme/normalize.md b/docs/readme/normalize.md index 8233a90..2725920 100644 --- a/docs/readme/normalize.md +++ b/docs/readme/normalize.md @@ -6,7 +6,6 @@ The `normalize` function will normalize an input bigwig file based on the follow * `zscore`: Set the mean value to 0 with a standard deviation of 1. * Variance-stabilizing transforms, provided for preparing **quantitative ChIP-seq target tracks** for `--quant` training and benchmarking: * `arcsinh`: inverse hyperbolic sine, `arcsinh(x)` - * `log2`: `log2(x) + 1` * `log1p`: natural log of one plus the value, `log(1 + x)` * `sqrt`: square root, `x^(1/2)` * `three_fourths`: `x^(3/4)` @@ -37,7 +36,7 @@ The name used to build the output filename. This can be any string; `.bw` is app ### `--method` -The method to use for normalization: `min-max`, `zscore`, `arcsinh`, `log2`, `log1p`, `sqrt`, `three_fourths` or `three_eighths` (see above). Default: `min-max` +The method to use for normalization: `min-max`, `zscore`, `arcsinh`, `log1p`, `sqrt`, `three_fourths` or `three_eighths` (see above). Default: `min-max` ### `--max_percentile` @@ -71,6 +70,10 @@ Define the chromosome sizes file. The current default file are the chromosome si The path to the blacklist bigwig file. This file is used to remove all the regions that are considered to have high technical noise. Default: maxATAC publication-defined blacklist. +### `--max_zooms` + +The number of zoom levels to compute for the normalized bigWig file. Zoom levels are pre-computed summary statistics that let genome browsers (IGV, UCSC Genome Browser) zoom in and out of a region quickly; fewer levels mean slower loading in browsers, more levels mean more memory during writing. Valid range: `0`-`10`. Default: `10`. Note: a value of `0` produces a bigWig that is not compatible with other bigWig tools (e.g. deepTools) and cannot be visualized in IGV or the UCSC Genome Browser. See the [pyBigWig README](https://github.com/deeptools/pyBigWig/blob/master/README.md) for details. + ### `-o`, `--output`, `--output_dir` Define the output directory. Default: the current working directory. diff --git a/docs/readme/peaks.md b/docs/readme/peaks.md index 754aeba..e90be0b 100644 --- a/docs/readme/peaks.md +++ b/docs/readme/peaks.md @@ -30,7 +30,7 @@ The threshold calibration table written by `maxatac threshold`, provided in `/da ### `-cutoff_type, --cutoff_type` -The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, or `F1`). Default: `F1`. +The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, `F1`, or `Peak_Recall`, the fraction of unique ChIP-seq peaks recovered). `Peak_Recall` needs a table written by a `maxatac threshold` version that includes it. Default: `F1`. ### `-cutoff_value, --cutoff_value` diff --git a/docs/readme/predict.md b/docs/readme/predict.md index d9cc310..91224e2 100644 --- a/docs/readme/predict.md +++ b/docs/readme/predict.md @@ -54,7 +54,7 @@ The threshold calibration table (`_cross_celltype.tsv`) written by [`max ### `-cutoff_type, --cutoff_type` -The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, or `F1`). Default: `F1`. +The metric whose calibration grid is used to pick the threshold (`Precision`, `Recall`, `F1`, or `Peak_Recall`, the fraction of unique ChIP-seq peaks recovered). `Peak_Recall` needs a table written by a `maxatac threshold` version that includes it. Default: `F1`. ### `-cutoff_value, --cutoff_value` @@ -64,6 +64,10 @@ The cutoff value for the cutoff type provided; precision, recall, and F1-scores Skip peak calling at the end of prediction, even when a calibration table is available. +### `--max_zooms` + +The number of zoom levels to compute for the prediction bigWig file. Zoom levels are pre-computed summary statistics that let genome browsers (IGV, UCSC Genome Browser) zoom in and out of a region quickly; fewer levels mean slower loading in browsers, more levels mean more memory during writing. Valid range: `0`-`10`. Default: `10`. Note: a value of `0` produces a bigWig that is not compatible with other bigWig tools (e.g. deepTools) and cannot be visualized in IGV or the UCSC Genome Browser. See the [pyBigWig README](https://github.com/deeptools/pyBigWig/blob/master/README.md) for details. + ### `-o, --output` Output directory path. Default: `./prediction_results` @@ -84,6 +88,10 @@ The windows to use for prediction. These windows must be 1,024 bp wide and have The number of regions to predict on per batch. Default: `10000`. Decrease this value if you are having memory issues. +### `--threads` + +The maximum number of chromosomes to predict in parallel. Each process loads the full model and the 2bit genome, so memory, not CPU count, usually sets the practical limit; lower this value if prediction runs out of memory. The pool is also capped by the number of chromosomes requested and the available CPUs. Default: `24` + ### `--step_size` The step size to use for building the prediction intervals. Overlapping prediction bins will be averaged together. Default: `INPUT_LENGTH/4` = 256 bp, where `INPUT_LENGTH` is the maxATAC model input size of 1,024 bp. diff --git a/docs/readme/threshold.md b/docs/readme/threshold.md index ccfa05b..b28679f 100644 --- a/docs/readme/threshold.md +++ b/docs/readme/threshold.md @@ -8,11 +8,19 @@ Because quantitative models output predicted ChIP-seq signal rather than probabi For every cell type listed in the meta file: -1. The prediction bigwig and the binary gold standard bigwig are binned at `--bin_size` (max per bin) on `--chromosomes`, excluding blacklisted bins. -2. A precision-recall curve is computed from the binned prediction scores against the binned gold standard, giving precision, recall, F1 and log2(precision / random precision) for every threshold. -3. The curve is re-binned on a 0.01 grid of Precision, Recall and F1 values so that each metric value maps to the threshold that achieves it. +1. The prediction bigwig and the binary gold standard bigwig are binned at `--bin_size` (max per bin) on the single held-out chromosome given by `--chromosomes`, excluding blacklisted bins. +2. A precision-recall curve is computed from the binned prediction scores against the binned gold standard: for every threshold, the precision, recall, F1 and log2(precision / random precision) **actually achieved at that threshold**. +3. Only thresholds worth using are kept. A threshold is dropped when a lower threshold reaches the same or a higher precision, because that lower threshold also has at least the recall (and Peak_Recall). On the kept rows, precision rises and recall falls as the threshold increases, and every row is a real threshold with the metrics it achieves: no value is carried over from another threshold. The final point of a precision-recall curve (Precision = 1, Recall = 0) belongs to no threshold and is not included, so a precision of 1 only appears if some threshold really reaches it. +4. Alongside the bin-level Recall, a peak-level **Peak_Recall** is computed per kept threshold: the fraction of unique ChIP-seq peaks with at least one non-blacklisted bin whose prediction is ≥ the threshold. Peaks are the unique intervals of the optional `ChIP_peaks` BED, or runs of consecutive gold-standard bins when it is not given. Fully blacklisted peaks are not counted. +5. The curve is re-binned on a 0.01 grid of Precision, Recall and Peak_Recall values, keeping the highest-F1 row in each bin. -The per-metric grids are then combined across cell types by taking the median threshold per grid bin (only thresholds are aggregated, never raw signal), producing the cross-cell-type table. `predict`/`peaks` look up the lowest grid bin that still meets the requested `--cutoff_value` (or the max-F1 bin when `--cutoff_type F1` is used without a value). +The per-cell-type grids are then combined into the cross-cell-type table: + +* Each cell type's grid is first extended to every bin from 0.00 to 1.00, so all cell types cover the same bins. Bins between two values the curve reaches are linearly interpolated. Bins beyond the curve's range repeat its nearest real row, so their `Precision`/`Recall` columns show what the cell type actually reaches, not the bin value. +* Per bin, the median `Precision`, `Recall`, `Threshold` and `Peak_Recall` across cell types is taken (only these per-threshold values are aggregated, never raw signal), and F1 is recomputed from the median precision and recall. A row therefore describes a typical cell type, not one particular cell type. +* The F1 grid is built from the Recall table by re-binning its rows on F1. + +`predict`/`peaks` look up a threshold by the **achieved** value of the requested metric, not by the bin label: among the rows of `--cutoff_type` whose achieved `Precision`, `Recall`, `F1` or `Peak_Recall` is ≥ `--cutoff_value`, they use the one closest to the request (ties go to the higher F1). If no row reaches the value, they stop with an error naming the highest value the table reaches. With `--cutoff_type F1` and no `--cutoff_value`, the max-F1 row is used. ## Meta file @@ -22,22 +30,24 @@ A tab-separated file with one row per cell type: | -------------- | ---------------------------------------------------------------------------------------------------- | | `Prediction` | Path to the prediction bigwig for this cell type (from `maxatac predict`, quantitative or binary) | | `Binding_File` | Path to the binary gold standard bigwig for this cell type (1 = TF bound, 0 = unbound) | +| `ChIP_peaks` | *(Optional)* ChIP-seq peak BED for this cell type, defining the unique peaks counted by `Peak_Recall`. If the column is missing or a cell is empty, runs of consecutive gold-standard bins are used as peaks (peaks less than one bin apart then merge) | -Additional columns (e.g. `Cell_Line`, `TF`) are ignored. Use validation cell types / chromosomes that were not used to train the model. +Additional columns (e.g. `Cell_Line`, `TF`) are ignored. Use validation cell types and a chromosome that were not used to train the model. ## Example ```bash -maxatac threshold --prefix CTCF --meta_file CTCF_threshold_meta.tsv --chromosomes chr2 chr19 --bin_size 200 --output ./threshold +maxatac threshold --prefix CTCF --meta_file CTCF_threshold_meta.tsv --chromosomes chr2 --bin_size 200 --output ./threshold ``` ## Outputs | Filename | Description | |-----------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| -| `_cross_celltype.tsv` | The calibration table used by `predict`/`peaks`. Columns: `Metric` (`Precision`, `Recall` or `F1`), `Bin` (metric value on the 0.01 grid), `Precision`, `Recall`, `Threshold`, `F1` | +| `_cross_celltype.tsv` | The calibration table used by `predict`/`peaks`. Columns: `Metric` (`Precision`, `Recall`, `F1` or `Peak_Recall`), `Bin` (position on the 0.01 grid of that metric), `Precision`, `Recall`, `Threshold`, `F1`, `Peak_Recall` (fraction of unique ChIP-seq peaks recovered at that threshold). The `Precision`/`Recall`/`F1`/`Peak_Recall` columns are the values achieved at `Threshold`; past the range a curve reaches they can be lower than `Bin` | | `.tsv` | The same table for each individual cell type in the meta file | -| `*_validationPerformance_vs_thresholdCalibration.png` | Precision, log2FC, recall and F1 vs. threshold for every cell type, with the cross-cell-type median in black | +| `_peak_recovery.tsv` | Per cell type: peak source, number of unique peaks, and `Peak_Recall` at that cell type's own max-F1 threshold and at the cross-cell-type max-F1 threshold | +| `*_validationPerformance_vs_thresholdCalibration.png` | Precision, recall, F1 and fraction of unique peaks recovered vs. threshold for every cell type, with the cross-cell-type median in black | ## Required Arguments @@ -53,7 +63,7 @@ The meta file described above. ### `--chromosomes` -The chromosomes used to calibrate the thresholds. Default: `chr2 chr19` (the default validation chromosomes). +The single held-out chromosome used to calibrate the thresholds. Exactly one chromosome must be given; `threshold` exits with an error otherwise. Default: `chr2`. ### `--bin_size` diff --git a/docs/readme/train.md b/docs/readme/train.md index fd67f68..3f53c57 100644 --- a/docs/readme/train.md +++ b/docs/readme/train.md @@ -33,7 +33,7 @@ General Steps: Every 1,024 bp training example is split into 32 bins of 32 bp. The per-bin target depends on the model type: * **`--quant` (quantitative model):** the target is the *mean* ChIP-seq signal of `Binding_File` across the 32 bp, multiplied by `--target_scale_factor`. The model uses a `softplus` output layer and a regression loss (`--loss`, default `mse`). Predictions are therefore on the same (scaled) units as the ChIP-seq targets. -* **Binary model (default):** the target is `1` if more than half of the 32 bp overlap a ChIP-seq peak in `Binding_File`, else `0`. The model uses a `sigmoid` output layer and cross-entropy loss (maxATAC v1 behaviour). +* **Binary model (default):** the target is `1` if more than half of the 32 bp overlap a ChIP-seq peak in `Binding_File` (the fraction is `BINARY_TARGET_MIN_PEAK_FRACTION = 0.5` in `maxatac/utilities/constants.py`; `Binding_File` must be a 0/1 peak track), else `0`. The model uses a `sigmoid` output layer and cross-entropy loss (maxATAC v1 behaviour). ### Model selection @@ -156,7 +156,7 @@ The weights to use to initialize a model. Default: `do not initialize with weigh ### `--epochs` -The number of epochs to train the model for. Default: `20` +The number of epochs to train the model for. Default: `100` ### `--batches` diff --git a/maxatac/analyses/average.py b/maxatac/analyses/average.py index a5fac11..036350a 100644 --- a/maxatac/analyses/average.py +++ b/maxatac/analyses/average.py @@ -24,7 +24,7 @@ def run_averaging(args): 4) Loop through each entry in the chromosome sizes dictionary and calculate the average across all inputs 5) Write the bigwig file - :param args: bigwig_files, output_dir, name, chromosomes, chromosome_sizes + :param args: bigwig_files, output_dir, name, chromosomes, chrom_sizes, max_zooms :return: A bigwig file """ @@ -50,7 +50,7 @@ def run_averaging(args): # Build a dictionary of chromosomes sizes using the chromosomes and chromosome sizes files provided # The function will filter the dictionary based on the input list - chromosome_sizes_dictionary = build_chrom_sizes_dict(args.chromosomes, args.chromosome_sizes) + chromosome_sizes_dictionary = build_chrom_sizes_dict(args.chromosomes, args.chrom_sizes) # Open the bigwig file for writing with pyBigWig.open(output_bigwig_filename, "w") as output_bw: @@ -60,7 +60,7 @@ def run_averaging(args): header = [(x, chromosome_sizes_dictionary[x]) for x in sorted(args.chromosomes)] # Write the header to the file - output_bw.addHeader(header) + output_bw.addHeader(header, maxZooms = args.max_zooms) # TODO Use parallel processing to speed up. Must write chromosomes in same order as header # Loop through the chromosomes and average the values across files @@ -89,7 +89,7 @@ def run_averaging(args): ends=chrom_length, span=1, step=1, - values=chrom_vals.tolist() + values=chrom_vals.astype(np.float16).tolist() ) # Measure time of averaging @@ -102,4 +102,4 @@ def run_averaging(args): logging.info("Total averaging time: %d:%d:%d.\n" % (hours, mins, secs)) - logging.info("Results saved to: " + output_bigwig_filename) \ No newline at end of file + logging.info("Results saved to: " + output_bigwig_filename) diff --git a/maxatac/analyses/benchmark.py b/maxatac/analyses/benchmark.py index 894b886..dde7736 100644 --- a/maxatac/analyses/benchmark.py +++ b/maxatac/analyses/benchmark.py @@ -38,7 +38,7 @@ def run_benchmarking(args): logging.info( "Benchmarking" + - "\n Prediction file: " + args.prediction + + "\n Prediction file: " + str(args.prediction) + "\n Alternative prediction file: " + str(args.alternative_prediction) + "\n Prediction combine operation: " + args.prediction_combine_operation + "\n Gold standard file: " + args.gold_standard + @@ -71,9 +71,10 @@ def run_benchmarking(args): else: for chromosome in args.chromosomes: logging.info("Benchmarking " + chromosome) - # Build the results filename + # Build the results filename; --random writes only the random baselines to their own file + results_suffix = "bp_random_UCPeR.tsv" if args.random else "bp_PRC.tsv" results_filename = os.path.join(output_dir, - args.prefix + "_" + chromosome + "_" + str(args.bin_size) + "bp_PRC.tsv") + args.prefix + "_" + chromosome + "_" + str(args.bin_size) + results_suffix) ChromosomeAUPRC(args.prediction, args.gold_standard, @@ -88,7 +89,8 @@ def run_benchmarking(args): plot=args.plot, peak_based=args.peak_based, alternative_prediction_bw=args.alternative_prediction, - prediction_combine_operation=args.prediction_combine_operation + prediction_combine_operation=args.prediction_combine_operation, + random_only=args.random ) # Measure End Time of Training diff --git a/maxatac/analyses/data.py b/maxatac/analyses/data.py index f410db5..b37e460 100644 --- a/maxatac/analyses/data.py +++ b/maxatac/analyses/data.py @@ -1,52 +1,263 @@ +import glob import shutil import os +import sys +import stat import logging -from maxatac.utilities.system_tools import get_dir, check_data_packages_installed - +import re +import subprocess +from maxatac.utilities.system_tools import get_dir, check_data_packages_installed, get_version +from maxatac.utilities.constants import V1_MODELS_WISHLIST_URL + +# Release and pre-release versions (2.0.0, 2.0.0b1, 2.0.0rc1, 2.0.0.post1) have a data repository tag of the +# same name; development versions (2.0.0.dev0, local versions such as 2.0.0+g1234abc) do not +RELEASE_VERSION = re.compile(r"\d+(\.\d+)*((a|b|rc)\d+)?(\.post\d+)?") + + +def remote_ref_exists(data_repo, ref): + """Check whether a git repository has a tag or branch with this name + + Args: + data_repo (str): Git repository URL or path + ref (str): Tag or branch name + + Returns: + bool: True if the tag or branch exists + """ + result = subprocess.run(["git", "ls-remote", "--tags", "--heads", data_repo, ref], + capture_output=True, text=True, check=True) + + return any(line.split("\t")[1] in (f"refs/tags/{ref}", f"refs/heads/{ref}") + for line in result.stdout.splitlines()) + + +def resolve_data_version(data_repo, data_version): + """Pick the data repository tag or branch to install + + Args: + data_repo (str): Git repository URL or path + data_version (str): --data_version: a tag or branch, "latest", or None for the tag matching this + quant-maxATAC version + + Returns: + str: Tag or branch to clone, or None to clone the latest commit on the default branch + """ + if data_version == "latest": + return None + + if data_version: + if not remote_ref_exists(data_repo, data_version): + raise ValueError(f"{data_repo} has no tag or branch named {data_version}. " + "Use --data_version latest for the newest data.") + + return data_version + + version = get_version() + + if not RELEASE_VERSION.fullmatch(version): + logging.warning(f"quant-maxATAC {version} is a development version: installing the latest data from " + f"{data_repo}. Use --data_version to install a specific release.") + return None + + tag = f"v{version}" + + if not remote_ref_exists(data_repo, tag): + logging.warning(f"{data_repo} has no {tag} tag matching quant-maxATAC {version}: installing the latest " + "data instead. Use --data_version to install a specific release.") + return None + + return tag + + +def remove_tree(path): + """Delete a directory tree, including read-only files such as git objects on Windows + + Args: + path (str): Directory to delete + """ + def make_writable_and_retry(func, failed_path, _): + os.chmod(failed_path, stat.S_IWRITE) + func(failed_path) + + if sys.version_info >= (3, 12): + shutil.rmtree(path, onexc=make_writable_and_retry) + else: + shutil.rmtree(path, onerror=make_writable_and_retry) + + +def describe_existing_data(data_dir): + """Summarize an existing maxATAC data directory so the user knows what will be overwritten + + Args: + data_dir (str): Path to the installed data directory. Default: ~/opt/maxatac/data + + Returns: + str: A short human readable description + """ + lines = [f"Existing maxATAC data found in: {data_dir}"] + + if os.path.isdir(os.path.join(data_dir, ".git")): + source = subprocess.run(["git", "remote", "get-url", "origin"], cwd=data_dir, + capture_output=True, text=True).stdout.strip() + + if source: + lines.append(f" Installed from: {source}") + + model_files = glob.glob(os.path.join(data_dir, "models", "*", "*.h5")) + + if model_files: + n_tfs = len({os.path.dirname(model_file) for model_file in model_files}) + + # quant-maxATAC ships a _cross_celltype.tsv calibration table next to each model; v1 (binary) models do not + n_v1 = len([model_file for model_file in model_files + if not glob.glob(os.path.join(os.path.dirname(model_file), "*_cross_celltype.tsv"))]) + + lines.append(f" Models: {len(model_files)} .h5 files for {n_tfs} TFs" + + (f", {n_v1} of which look like maxATAC v1 (binary) models" if n_v1 else "")) + + return "\n".join(lines) + + +def confirm_overwrite(data_dir, assume_yes): + """Ask the user to confirm that an existing data directory, including any v1 models, will be replaced + + Args: + data_dir (str): Path to the installed data directory + assume_yes (bool): Skip the prompt (--yes) + + Returns: + bool: True if the data directory may be overwritten + """ + logging.warning(describe_existing_data(data_dir)) + + if assume_yes: + logging.info("--yes was set: overwriting without asking") + return True + + if not sys.stdin.isatty(): + raise RuntimeError(f"{data_dir} already exists and would be overwritten, but there is no terminal to " + "confirm this. Re-run with --yes to overwrite it.") + + try: + answer = input(f"\n{data_dir} will be overwritten, including any maxATAC v1 models it contains.\n" + f"quant-maxATAC does not use the v1 models; to ask for v1 support, see {V1_MODELS_WISHLIST_URL}\n" + "Continue? [y/N] ") + + except EOFError: + # No answer could be read (e.g. stdin is a null device on Windows): treat it as "no" + logging.error("No answer received. Re-run with --yes to overwrite without asking.") + return False + + return answer.strip().lower() in ("y", "yes") + + def run_data(args): - """Download maxATAC reference data + """Download maxATAC reference data and the quant-maxATAC models + + Workflow overview + + 1) Pick the data version: --data_version, or the data repository tag matching this quant-maxATAC version + 2) If a data directory already exists, ask the user to confirm it will be overwritten (v1 models included) + 3) Clone that version of the data repository into a temporary directory, so a failed clone leaves the old + data in place + 4) Replace the old data directory with the new clone, keeping any downloaded .2bit files + 5) Download the UCSC .2bit genome sequence for each requested genome Args: - args (Namespace): Arguments list for the reference genome and the log level. - """ + args (Namespace): Arguments list for the reference genome, output directory, data repository, data version, + --yes and the log level. + """ check_data_packages_installed() ############### Parameters ############### # Path to the directory where the project data should be installed. Default: ~/opt base_dir = get_dir(args.output) - + # Path to the maxATAC directory in the install directory. Default: ~/opt/maxatac maxatac_dir = get_dir(os.path.join(base_dir, "maxatac")) - - # Path the repo directory and the final directory. Default: ~/opt/maxatac/maxATAC_data - maxatac_repo_dir = os.path.join(maxatac_dir, "maxATAC_data") - - # Path final directory (it is renamed for simplicity). Default: ~/opt/maxatac/data - maxatac_final_dir = os.path.join(maxatac_dir, "data") - # Command to clone the data repo - clone = "git clone --depth 1 https://github.com/MiraldiLab/maxATAC_data.git" + # Final data directory. Default: ~/opt/maxatac/data + maxatac_final_dir = os.path.join(maxatac_dir, "data") - os.chdir(maxatac_dir) # Change to the directory where the repo should be cloned - - os.system(clone) # Cloning + # Temporary clone directory, swapped in for the final directory once the clone succeeded + maxatac_tmp_dir = os.path.join(maxatac_dir, ".maxatac_data.tmp") - dest = shutil.move(maxatac_repo_dir, maxatac_final_dir) # Rename the git directory to data + # The old data directory is renamed here before the new one is moved in, and deleted last + maxatac_old_dir = os.path.join(maxatac_dir, ".maxatac_data.old") # Set all genomes if selected - if args.genome == ['all']: - args.genome = ["hg38", "hg19", "mm10"] + genomes = ["hg38", "hg19", "mm10"] if args.genome == ['all'] else args.genome + + ############### Body ############### + # Resolve the version first, so a bad --data_version fails before anything is asked or changed + data_ref = resolve_data_version(args.data_repo, args.data_version) + data_label = data_ref or "latest" + + if os.path.isdir(maxatac_final_dir) and os.listdir(maxatac_final_dir): + if not confirm_overwrite(maxatac_final_dir, args.yes): + logging.info("Aborted: nothing was changed.") + return + + # Clear temporary directories left behind by an interrupted run + for leftover_dir in (maxatac_tmp_dir, maxatac_old_dir): + if os.path.exists(leftover_dir): + remove_tree(leftover_dir) + + logging.info(f"Cloning {args.data_repo} ({data_label}) \n" + + f"Final data will be placed in: {maxatac_final_dir}") + + branch = ["--branch", data_ref] if data_ref else [] + + try: + # advice.detachedHead=false: cloning a tag is expected, not worth git's detached HEAD notice + subprocess.run(["git", "-c", "advice.detachedHead=false", "clone", "--depth", "1", *branch, + args.data_repo, maxatac_tmp_dir], check=True) + + except subprocess.CalledProcessError: + if os.path.exists(maxatac_tmp_dir): + remove_tree(maxatac_tmp_dir) + raise + + if os.path.isdir(maxatac_final_dir): + # The .2bit files are not part of the repository and are large: carry them over instead of re-downloading + for twobit in glob.glob(os.path.join(maxatac_final_dir, "*", "*.2bit")): + new_genome_dir = os.path.join(maxatac_tmp_dir, os.path.basename(os.path.dirname(twobit))) + + if os.path.isdir(new_genome_dir) and not os.path.exists(os.path.join(new_genome_dir, os.path.basename(twobit))): + shutil.move(twobit, new_genome_dir) + + # Swap by renaming, so the data directory is never left half deleted + shutil.move(maxatac_final_dir, maxatac_old_dir) + + shutil.move(maxatac_tmp_dir, maxatac_final_dir) + + if os.path.exists(maxatac_old_dir): + remove_tree(maxatac_old_dir) + + commit = subprocess.run(["git", "rev-parse", "HEAD"], cwd=maxatac_final_dir, + capture_output=True, text=True).stdout.strip() + + logging.info(f"Installed {args.data_repo} {data_label} at commit {commit}") + + for genome in genomes: + genome_dir = os.path.join(maxatac_final_dir, genome) + + if not os.path.isdir(genome_dir): + logging.warning(f"{args.data_repo} has no reference data for {genome}; skipping the {genome}.2bit download") + continue + + if os.path.exists(os.path.join(genome_dir, f"{genome}.2bit")): + logging.info(f"{genome}.2bit is already present in {genome_dir}") + continue - for genome in args.genome: - os.chdir(os.path.join(maxatac_final_dir, genome)) # change to the final data directory - wget_2bit = f"wget --no-check-certificate https://hgdownload.cse.ucsc.edu/goldenpath/{genome}/bigZips/{genome}.2bit -O {genome}.2bit" + logging.info(f"Downloading {genome}.2bit into {genome_dir}") - ############### Body ############### - logging.info(f"Downloading data for: {genome} \n" + - f"Data will be installed: {args.output} \n" + - f"Temporarily downlading data to: {maxatac_repo_dir} \n" + - f"Final data will be placed in: {maxatac_final_dir}") + # Download under a temporary name so an interrupted download is not mistaken for a finished one + subprocess.run(["wget", "--no-check-certificate", + f"https://hgdownload.cse.ucsc.edu/goldenpath/{genome}/bigZips/{genome}.2bit", + "-O", f"{genome}.2bit.part"], + cwd=genome_dir, check=True) - os.system(wget_2bit) # Wget 2bit + os.replace(os.path.join(genome_dir, f"{genome}.2bit.part"), os.path.join(genome_dir, f"{genome}.2bit")) logging.info("Finished!") diff --git a/maxatac/analyses/normalize.py b/maxatac/analyses/normalize.py index 9360acf..b698406 100644 --- a/maxatac/analyses/normalize.py +++ b/maxatac/analyses/normalize.py @@ -7,7 +7,7 @@ from maxatac.utilities.system_tools import get_dir, Mute from maxatac.utilities.genome_tools import build_chrom_sizes_dict, chromosome_blacklist_mask from maxatac.utilities.normalization_tools import minmax_normalize_array, zscore_normalize_array, get_genomic_stats, \ - arcsinh_normalize_array, log2_normalize_array, log1p_normalize_array, sqrt_normalize_array, three_fourth_normalize_array, \ + arcsinh_normalize_array, log1p_normalize_array, sqrt_normalize_array, three_fourth_normalize_array, \ three_eighths_normalize_array @@ -31,7 +31,7 @@ def run_normalization(args): 3) Find the genomic min and max values by looping through each chromosome 5) Loop through each chromosome and minmax normalize the values based on the genomic values. - :param args: signal, output_dir, chromosome_sizes, chromosomes, max_percentile, method, blacklist + :param args: signal, output_dir, chromosome_sizes, chromosomes, max_percentile, method, blacklist, max_zooms :return: A minmax normalized bigwig file """ @@ -84,7 +84,7 @@ def run_normalization(args): with pyBigWig.open(args.signal) as input_bw, pyBigWig.open(output_filename, "w") as output_bw: header = [(x, chromosome_length_dictionary[x]) for x in sorted(args.chromosomes)] - output_bw.addHeader(header) + output_bw.addHeader(header, maxZooms = args.max_zooms) # For every chromosome in header, perform normalization for chrom_name, chrom_length in header: @@ -99,9 +99,6 @@ def run_normalization(args): elif args.method == "arcsinh": normalized_signal = arcsinh_normalize_array(chr_vals) - elif args.method == "log2": - normalized_signal = log2_normalize_array(chr_vals) - elif args.method == "log1p": normalized_signal = log1p_normalize_array(chr_vals) @@ -131,7 +128,7 @@ def run_normalization(args): ends=chrom_length, span=1, step=1, - values=normalized_signal.tolist() + values=normalized_signal.astype(np.float16).tolist() ) # Measure time of averaging diff --git a/maxatac/analyses/peaks.py b/maxatac/analyses/peaks.py index 4a7bff0..f02eff7 100644 --- a/maxatac/analyses/peaks.py +++ b/maxatac/analyses/peaks.py @@ -16,7 +16,7 @@ def run_call_peaks(args): chromosomes: The list of chromosomes to call peaks for BIN_SIZE: The size of the bin to use for peak calling prefix: The prefix for the output filename - cutoff_type: Choose between Precision, Recall, and F1 to choose your cutoffs + cutoff_type: Choose between Precision, Recall, F1, and Peak_Recall to choose your cutoffs cutoff_value: The value associated to cutoff type, i.e. Precision 0.75 cutoff_file: Threshold calibration table written by `maxatac threshold`, i.e. /maxATAC/data/models/YOUR_TF_MODEL/YOUR_TF_MODEL_cross_celltype.tsv diff --git a/maxatac/analyses/predict.py b/maxatac/analyses/predict.py index d969c45..f2aefec 100644 --- a/maxatac/analyses/predict.py +++ b/maxatac/analyses/predict.py @@ -51,7 +51,15 @@ def run_prediction(args): # If the user provides the TF name, if args.TF: - args.model = glob.glob(os.path.join(args.DATA_PATH, "models", args.TF, args.TF + "*.h5"))[0] + model_files = glob.glob(os.path.join(args.DATA_PATH, "models", args.TF, args.TF + "*.h5")) + + if not model_files: + raise FileNotFoundError( + f"No model (*.h5) found for {args.TF} in {os.path.join(args.DATA_PATH, 'models', args.TF)}. " + "Download the models with `maxatac data`, or pass a model with --model." + ) + + args.model = model_files[0] # An explicitly provided --cutoff_file wins; only fall back to the bundled table. if not args.cutoff_file: @@ -128,12 +136,18 @@ def run_prediction(args): "Chromosomes in final prediction set: \n - " + "\n -".join(chrom_list) + "\n" + f"Output directory: {output_directory} \n" + f"Batch Size: {args.batch_size} \n" + + f"Threads: {args.threads} \n" + f"Ablation type: {args.ablation_type} \n" + f"Ablation value: {args.ablation_value} \n" + f"Output filename: {outfile_name_bigwig}" ) - with Pool(int(multiprocessing.cpu_count())) as p: + # One worker per chromosome, capped by --threads: every worker loads the full model and the + # 2bit genome, so the pool is bounded by memory rather than by cores. + n_workers = max(1, min(args.threads, len(chrom_list), multiprocessing.cpu_count())) + logging.info(f"Predicting {len(chrom_list)} chromosome(s) with {n_workers} process(es) (--threads {args.threads})") + + with Pool(n_workers) as p: forward_strand_predictions = p.starmap(make_stranded_predictions, [(regions_pool, args.signal, @@ -155,7 +169,8 @@ def run_prediction(args): write_predictions_to_bigwig(prediction_bedgraph, output_filename=outfile_name_bigwig, chrom_sizes_dictionary=chrom_sizes_dict, - chromosomes=chrom_list + chromosomes=chrom_list, + max_zooms = args.max_zooms ) # If a cutoff file is provided, call peaks @@ -192,7 +207,6 @@ def run_prediction(args): index=False, header=False) - # Measure end time of training stopTime = timeit.default_timer() totalTime = stopTime - startTime diff --git a/maxatac/analyses/prepare.py b/maxatac/analyses/prepare.py index adb0995..f8ca07a 100644 --- a/maxatac/analyses/prepare.py +++ b/maxatac/analyses/prepare.py @@ -15,7 +15,7 @@ import pysam from maxatac.utilities.system_tools import get_dir, check_prepare_packages_installed from maxatac.utilities.prepare_tools import convert_fragments_to_tn5_bed -from maxatac.utilities.constants import PREPARE_scATAC_SCRIPT, PREPARE_BULK_SCRIPT +from maxatac.utilities.constants import PREPARE_scATAC_SCRIPT, PREPARE_BULK_SCRIPT, DEFAULT_MAX_ZOOMS from maxatac.analyses.normalize import run_normalization @@ -154,6 +154,7 @@ def run_prepare(args): args.max = False args.max_percentile = 99 args.clip = False + args.max_zooms = DEFAULT_MAX_ZOOMS # Minmax normalize signal tracks run_normalization(args) diff --git a/maxatac/analyses/threshold.py b/maxatac/analyses/threshold.py index 60b0516..73f9269 100644 --- a/maxatac/analyses/threshold.py +++ b/maxatac/analyses/threshold.py @@ -2,11 +2,11 @@ import pandas as pd import os import multiprocessing -from multiprocessing import Pool, Manager +from multiprocessing import Pool import time from maxatac.utilities.genome_tools import build_chrom_sizes_dict, get_bigwig_stats from maxatac.utilities.system_tools import get_dir -from maxatac.utilities.threshold_tools import import_blacklist_mask, import_GoldStandard_array, calculate_AUC_per_rank, compute_calibration_curve, bin_curve_by_metric, extend_bins_to_full_grid, bin_median_table_by_f1, merge_binned_metrics, build_cross_cell_type_threshold_table +from maxatac.utilities.threshold_tools import import_blacklist_mask, import_GoldStandard_array, calculate_AUC_per_rank, compute_calibration_curve, bin_curve_by_metric, extend_bins_to_full_grid, bin_median_table_by_f1, merge_binned_metrics, build_cross_cell_type_threshold_table, import_peak_bed_bins, gold_standard_run_bins, peak_max_predictions, peak_recall_at_thresholds from maxatac.utilities.plot import plot_threshold_calibration_stats from sklearn.metrics import precision_recall_curve from sklearn import metrics @@ -14,79 +14,103 @@ import logging -def extract_pred_gs_bw(bigwig_file, training_data_dict, chrom_name, chrom_length, bin_count): +def extract_pred_gs_bw(bigwig_file, training_data_dict, chrom_name, chrom_length, bin_count, + peaks_bed=None, blacklist_mask=None): + """ + Bin one cell type's prediction bigwig and its binary gold standard on one chromosome, and + reduce the prediction to one max value per unique ChIP-seq peak (for Peak_Recall). + + Peaks come from peaks_bed (unique BED intervals) when given, else from runs of consecutive + gold-standard bins. Blacklisted bins are ignored; fully blacklisted peaks are dropped. + + :return: (predictions, gold_standard, tot_gs_bins, peak_max, peak_source) with predictions + and gold_standard both of length bin_count and aligned bin-for-bin. + """ start = time.time() - bw_name = bigwig_file.split("/")[-1] - chrom_vals = get_bigwig_stats(bigwig_file, chrom_name, chrom_length, bin_count) - print(training_data_dict[bigwig_file]) - - - predictions = np.empty(1, dtype=np.float64) - gold_standard = np.empty(1, dtype=np.float64) - goldstandard_array = import_GoldStandard_array(training_data_dict[bigwig_file], chrom_name, chrom_length, bin_count) - - tot_gs_bins = len(np.argwhere(goldstandard_array == True)) - - predictions = np.concatenate([predictions, chrom_vals]) - gold_standard = np.concatenate([gold_standard, goldstandard_array]) - - end = time.time() - print('total time (s)= ' + str(end-start), "____________", bw_name) - - return predictions, gold_standard, tot_gs_bins + bw_name = os.path.basename(bigwig_file) + + predictions = get_bigwig_stats(bigwig_file, chrom_name, chrom_length, bin_count) + gold_standard = import_GoldStandard_array(training_data_dict[bigwig_file], chrom_name, chrom_length, bin_count) + + tot_gs_bins = int(np.count_nonzero(gold_standard)) + + if peaks_bed: + peak_idx, bin_idx = import_peak_bed_bins(peaks_bed, chrom_name, chrom_length, bin_count) + peak_source = os.path.basename(peaks_bed) + else: + peak_idx, bin_idx = gold_standard_run_bins(gold_standard) + peak_source = "gold_standard_runs" + peak_max = peak_max_predictions(predictions, peak_idx, bin_idx, keep_mask=blacklist_mask) + + logging.info(f"Binned {bw_name} vs {os.path.basename(training_data_dict[bigwig_file])} " + f"on {chrom_name} in {time.time() - start:.1f} s; " + f"{len(peak_max)} unique peaks from {peak_source}") + + return predictions, gold_standard, tot_gs_bins, peak_max, peak_source def run_thresholding(args): """ :param args: :return: """ + # Calibration is done on exactly one held-out chromosome: the per-cell-type arrays, + # the blacklist mask and the random-precision denominator all refer to that chromosome. + if len(args.chromosomes) != 1: + raise ValueError("maxatac threshold calibrates on exactly one chromosome; " + f"got --chromosomes {' '.join(args.chromosomes)}") + # Make the output directory output_dir = get_dir(args.output_dir) chromosome_sizes_dictionary = build_chrom_sizes_dict(args.chromosomes, args.chrom_sizes) + (chrom_name, chrom_length), = chromosome_sizes_dictionary.items() meta_DF = pd.read_table(args.meta_file) training_data_dict = pd.Series(meta_DF["Binding_File"].values,index=meta_DF["Prediction"]).to_dict() - # Loop through the chromosomes and average the values across files - OUT=[] - for chrom_name, chrom_length in chromosome_sizes_dictionary.items(): - bin_count = int(int(chrom_length) / int(args.bin_size)) # need to floor the number - - blacklist_mask = import_blacklist_mask(args.blacklist_bw, chrom_name, chrom_length, bin_count) + # Optional ChIP_peaks column (BED) defines the unique peaks for Peak_Recall; a missing + # column or empty cell falls back to runs of consecutive gold-standard bins. + if "ChIP_peaks" in meta_DF.columns: + peaks_dict = {pred: (bed if isinstance(bed, str) and bed.strip() else None) + for pred, bed in zip(meta_DF["Prediction"], meta_DF["ChIP_peaks"])} + else: + peaks_dict = {} - lst_of_bws=list(training_data_dict.keys()) - - pool = Pool(int(multiprocessing.cpu_count())) + bin_count = int(int(chrom_length) / int(args.bin_size)) # need to floor the number + + blacklist_mask = import_blacklist_mask(args.blacklist_bw, chrom_name, chrom_length, bin_count) + + lst_of_bws = list(training_data_dict.keys()) + + # Bin every cell type's prediction and gold standard in parallel + with Pool(int(multiprocessing.cpu_count())) as pool: output = pool.starmap( extract_pred_gs_bw, - [(bigwig, training_data_dict, chrom_name, chrom_length, bin_count) for bigwig in lst_of_bws] - ) - OUT.append(output) - + [(bigwig, training_data_dict, chrom_name, chrom_length, bin_count, + peaks_dict.get(bigwig), blacklist_mask) for bigwig in lst_of_bws] + ) # Stack each cell type's Prediction/GoldStandard as a pair of columns - DF=pd.DataFrame([]) + DF = pd.DataFrame([]) total_gs_bins = [] - for i in range(len(OUT[0])): - df = pd.DataFrame([]) - - df['Prediction'] = OUT[0][i][0][:bin_count].tolist() - df['GoldStandard'] = OUT[0][i][1][:bin_count].tolist() - - gs_bins = OUT[0][i][2] + peak_maxes = [] + peak_sources = [] + for predictions, gold_standard, gs_bins, peak_max, peak_source in output: + df = pd.DataFrame({'Prediction': predictions, 'GoldStandard': gold_standard}) DF = pd.concat([DF, df], axis=1, ignore_index=True) total_gs_bins.append(gs_bins) + peak_maxes.append(peak_max) + peak_sources.append(peak_source) - num_cell_types = len(OUT[0]) + num_cell_types = len(output) # Create a bedtools object that is a windowed genome BED_df_bedtool = pybedtools.BedTool().window_maker(g=args.chrom_sizes, w=args.bin_size) - # Create a blacklist object form the blacklist bed - # TODO: I do not think we need to get the blacklist bed location like this since it is a part of the args now. - blacklist_bed_location = ".".join([args.blacklist_bw.split(".")[0],'bed']) + # Create a blacklist object form the blacklist bed: --blacklist_bed if given, otherwise the .bed next to --blacklist_bw. + # splitext only strips the final extension, so dots elsewhere in the path are kept. + blacklist_bed_location = args.blacklist_bed or os.path.splitext(args.blacklist_bw)[0] + ".bed" blacklist_bedtool = pybedtools.BedTool(blacklist_bed_location) # Remove the blacklisted regions from the windowed genome object @@ -98,15 +122,16 @@ def run_thresholding(args): # Rename the columns df.columns = ["chr", "start", "stop"] - # Find the number of non-blacklisted bins in chr of interest (log2FC denominator) - rand_bins = df.query('chr == @args.chromosomes').shape[0] + # Find the number of non-blacklisted bins in the chromosome of interest (log2FC denominator) + rand_bins = df.query('chr == @chrom_name').shape[0] logging.info("Building per-cell-type calibration curves") raw_cell_type_curves = [] for i in range(num_cell_types): ct_curve = compute_calibration_curve( - DF[2 * i + 1][blacklist_mask], DF[2 * i][blacklist_mask], total_gs_bins[i], rand_bins + DF[2 * i + 1][blacklist_mask], DF[2 * i][blacklist_mask], total_gs_bins[i], rand_bins, + peak_max=peak_maxes[i] ) raw_cell_type_curves.append(ct_curve) @@ -118,33 +143,49 @@ def run_thresholding(args): cross_celltype_filename = os.path.join(output_dir, args.prefix + "_cross_celltype.tsv") cross_celltype_table.to_csv(cross_celltype_filename, sep="\t", header=True, index=False) + # Per-cell-type % of unique ChIP-seq peaks recovered at its own max-F1 threshold and at + # the cross-cell-type max-F1 threshold + cross_f1 = cross_celltype_table[cross_celltype_table['Metric'] == 'F1'] + cross_best_threshold = cross_f1.loc[cross_f1['F1'].idxmax(), 'Threshold'] + peak_recovery_rows = [] + for i, ct_curve in enumerate(raw_cell_type_curves): + own_best = ct_curve.loc[ct_curve['F1'].idxmax()] + peak_recovery_rows.append({ + 'Prediction': os.path.basename(lst_of_bws[i]), + 'Peak_Source': peak_sources[i], + 'N_Peaks': len(peak_maxes[i]), + 'MaxF1_Threshold': own_best['Threshold'], + 'MaxF1': own_best['F1'], + 'Peak_Recall_at_MaxF1': own_best['Peak_Recall'], + 'CrossCellType_MaxF1_Threshold': cross_best_threshold, + 'Peak_Recall_at_CrossCellType_MaxF1': peak_recall_at_thresholds(peak_maxes[i], [cross_best_threshold])[0], + }) + pd.DataFrame(peak_recovery_rows).to_csv(os.path.join(output_dir, args.prefix + "_peak_recovery.tsv"), + sep="\t", header=True, index=False) + logging.info("Plotting the validation statistics v. threshold values") # Plot each cell type's own binned+extended curve rather than resampling it at the # median thresholds, so one cell type's gaps cannot distort another's line. cell_type_curves = [] for i, ct_curve in enumerate(raw_cell_type_curves): - random_precision_i = total_gs_bins[i] / rand_bins precision_curve = extend_bins_to_full_grid(bin_curve_by_metric(ct_curve, 'Precision')) recall_curve = extend_bins_to_full_grid(bin_curve_by_metric(ct_curve, 'Recall')) + peak_recall_curve = extend_bins_to_full_grid(bin_curve_by_metric(ct_curve, 'Peak_Recall')) # Save this cell type's own binned threshold table (same schema as cross_celltype.tsv) - sample_table = merge_binned_metrics([precision_curve, recall_curve, bin_median_table_by_f1([recall_curve])]) + sample_table = merge_binned_metrics([precision_curve, recall_curve, bin_median_table_by_f1([recall_curve]), + peak_recall_curve]) sample_name = os.path.splitext(os.path.basename(lst_of_bws[i]))[0] sample_table.to_csv(os.path.join(output_dir, sample_name + ".tsv"), sep="\t", header=True, index=False) # F1 is not monotonic in Threshold, so re-binning it by value zigzags; the # Recall-binned curve already carries a Threshold-monotonic F1 column, reuse it. - curves_by_metric = {'Precision': precision_curve, 'Recall': recall_curve, 'F1': recall_curve.copy()} - for curve in curves_by_metric.values(): - curve['log2FC'] = np.log2(curve['Precision'] / random_precision_i) + curves_by_metric = {'Precision': precision_curve, 'Recall': recall_curve, 'F1': recall_curve.copy(), + 'Peak_Recall': peak_recall_curve} cell_type_curves.append({'name': os.path.basename(lst_of_bws[i]), 'curves': curves_by_metric}) - # log2FC is needed for the plot only; not written to cross_celltype.tsv - random_precision = np.mean(total_gs_bins) / rand_bins - median_curve_for_plot = cross_celltype_table.copy() - median_curve_for_plot['log2FC'] = np.log2(median_curve_for_plot['Precision'] / random_precision) - - plot_threshold_calibration_stats(median_curve_for_plot, cell_type_curves, cross_celltype_filename, args.prefix) + plot_threshold_calibration_stats(cross_celltype_table, cell_type_curves, cross_celltype_filename, args.prefix, + chrom_name=chrom_name) diff --git a/maxatac/analyses/train.py b/maxatac/analyses/train.py index 8c4891b..b2ee012 100644 --- a/maxatac/analyses/train.py +++ b/maxatac/analyses/train.py @@ -1,8 +1,11 @@ import logging -import sys import timeit -from tensorflow.python.keras.utils.data_utils import OrderedEnqueuer +try: + from tensorflow.keras.utils import OrderedEnqueuer # public API on Keras 2 (TF <= 2.15, or tf_keras) +except ImportError: + # Keras 3 (TF >= 2.16) dropped the public name; TF still ships the legacy copy + from tensorflow.python.keras.utils.data_utils import OrderedEnqueuer from maxatac.utilities.constants import TRAIN_MONITOR, INPUT_LENGTH from maxatac.utilities.system_tools import Mute @@ -246,6 +249,4 @@ def run_training(args): mins, secs = divmod(totalTime, 60) hours, mins = divmod(mins, 60) - logging.info("Total training time: %d:%d:%d.\n" % (hours, mins, secs)) - - sys.exit() \ No newline at end of file + logging.info("Total training time: %d:%d:%d.\n" % (hours, mins, secs)) \ No newline at end of file diff --git a/maxatac/analyses/variants.py b/maxatac/analyses/variants.py index e1e0a50..cea2e26 100644 --- a/maxatac/analyses/variants.py +++ b/maxatac/analyses/variants.py @@ -14,7 +14,7 @@ def run_variants(args): Args: args ([type]): input_bigwig, sequence, models, chromosomes, variant_start_pos, nucleotide, overhang, output, name """ - output_directory = get_dir(args.output) + output_directory = get_dir(args.output_dir) output_bw = os.path.join(output_directory, args.name + ".bw") output_bg = os.path.join(output_directory, args.name + ".bg") output_windows = os.path.join(output_directory, args.name + "_windows.bed") @@ -42,7 +42,8 @@ def run_variants(args): bed_df = create_prediction_regions(chromosomes=args.chromosomes, chrom_sizes=args.chrom_sizes, blacklist=args.blacklist, - step_size=args.step_size + peaks=None, + windows=None ) regions_pool = pybedtools.BedTool.from_dataframe(bed_df) diff --git a/maxatac/architectures/dcnn.py b/maxatac/architectures/dcnn.py index 8b234dc..cea697c 100644 --- a/maxatac/architectures/dcnn.py +++ b/maxatac/architectures/dcnn.py @@ -43,9 +43,22 @@ def pearson(y_true, y_pred): return score def spearman(y_true, y_pred): + """ + Spearman correlation over all values in the batch, as a scalar metric. scipy's spearmanr + on 2-D inputs returns a (correlation matrix, p-value matrix) pair, so flatten first. + """ from scipy.stats import spearmanr - - return ( tf.py_function(spearmanr, [tf.cast(y_pred, tf.float32), tf.cast(y_true, tf.float32)], Tout = tf.float32) ) + import numpy as np + + def _spearman(a, b): + rho = spearmanr(a.numpy().ravel(), b.numpy().ravel())[0] + # A constant batch has no rank correlation; report 0 rather than NaN so one + # degenerate batch does not poison the epoch mean. + return np.float32(0.0 if np.isnan(rho) else rho) + + score = tf.py_function(_spearman, [tf.cast(y_true, tf.float32), tf.cast(y_pred, tf.float32)], Tout=tf.float32) + score.set_shape(()) + return score def dice_coef( y_true, @@ -356,9 +369,8 @@ def get_dilated_cnn( beta_2=adam_beta_2, weight_decay=adam_decay ), - run_eagerly=True, # TODO: for debugging loss fn remove loss=loss_function, - metrics=[loss_function, coeff_determination, pearson, spearman] #mse + metrics=[coeff_determination, pearson, spearman] # tf.keras.metrics.RootMeanSquaredError(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall(), # Can not use Precision and Recall metrics with quant models and a softplus activation since values will # go greater than 1, will kick back an error diff --git a/maxatac/utilities/benchmarking_tools.py b/maxatac/utilities/benchmarking_tools.py index 54866ac..523281f 100644 --- a/maxatac/utilities/benchmarking_tools.py +++ b/maxatac/utilities/benchmarking_tools.py @@ -6,7 +6,7 @@ from maxatac.utilities.genome_tools import load_bigwig, chromosome_blacklist_mask, chromosome_whitelist_mask, import_prediction_array_fn, import_quant_goldstandard_array_fn from sklearn import metrics from sklearn.metrics import precision_recall_curve, r2_score, mean_absolute_error -from scipy import stats +from scipy import stats, special from scipy.stats import pearsonr, spearmanr from maxatac.utilities.system_tools import remove_tags import pybedtools @@ -16,15 +16,24 @@ def Precision_for_Recall(df, percent_recall): - percent_recall = percent_recall - upper_lim_recall = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Recall.tolist()[0] - lower_lim_recall = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Recall.tolist()[1] - upper_lim_precision = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Precision.tolist()[0] - lower_lim_precision = df.iloc[(df['Recall'] - percent_recall).abs().argsort()[:2]].Precision.tolist()[1] - val = (upper_lim_precision * abs(percent_recall - upper_lim_recall) + lower_lim_precision * abs( - percent_recall - lower_lim_recall)) / 2 - sp_precision = lower_lim_precision + val - return sp_precision + """ + Precision at a given recall, linearly interpolated between the two points of the + precision-recall curve that bracket percent_recall. Outside the curve's recall range the + nearest endpoint's precision is returned. + + :param df: DataFrame with 'Recall' and 'Precision' columns (any order) + :param percent_recall: recall at which to evaluate precision, e.g. 0.1 + """ + curve = df[['Recall', 'Precision']].dropna().sort_values('Recall') + recall = curve['Recall'].to_numpy() + precision = curve['Precision'].to_numpy() + + # Collapse duplicate recall values (a PR curve is a step function) to their max precision + # so np.interp sees strictly increasing x. + unique_recall, first_idx = np.unique(recall, return_index=True) + max_precision = np.maximum.reduceat(precision, first_idx) + + return float(np.interp(percent_recall, unique_recall, max_precision)) def calculate_sse(vector1, vector2): """ @@ -91,6 +100,10 @@ def __init__(self, self.quant_gs_null = quant_gs_null # change to quant_null_model self.prediction_combine_operation = prediction_combine_operation + if prediction_combine_operation == "rank_max": + raise ValueError("prediction_combine_operation rank_max is for the precision-recall benchmark only; " + "R2, Pearson and Spearman need prediction values, not percentile ranks") + # This has been modified self.blacklist_mask = chromosome_blacklist_mask(blacklist_bw, self.chromosome, @@ -282,16 +295,18 @@ def __plot__(self): x = plot_df.y_obs y = plot_df.y_pred - # Fit a line of best fit - (m, b), (SSE,), *_ = np.polyfit(x, y, deg=1, full=True) - # set y-intercept = 0 - b=0 + # Least-squares fit of y = m * x through the origin, and the SSE of that line + x_arr = np.asarray(x, dtype=float) + y_arr = np.asarray(y, dtype=float) + m = float(np.dot(x_arr, y_arr) / np.dot(x_arr, x_arr)) + b = 0 + SSE = float(np.sum((y_arr - m * x_arr) ** 2)) from matplotlib.ticker import MaxNLocator import matplotlib.ticker as ticker # Generate values for the line of best fit xseq = np.linspace(min(x) - 1, max(x) + 1, num=100) - ax.plot(xseq, m * xseq + b, color='r', lw=2.5, label=f'Best Fit: y = {m:.2f}x + {b:.2f}\nSSE = {SSE:.2f}') + ax.plot(xseq, m * xseq + b, color='r', lw=2.5, label=f'Best Fit: y = {m:.2f}x\nSSE = {SSE:.2f}') ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.xaxis.set_major_locator(MaxNLocator(integer=True)) @@ -430,6 +445,73 @@ def precision_recall_curve_peak_based(y_member, y_score): # return precision, recall, thresholds +def random_ucper_curve(y_member, n_points=2000): + """ + Expected precision vs unique-peak recall curve of a random ranking, built the same way as + precision_recall_curve_peak_based. + + Unlike bin-level AUPRC the random curve is not flat. A peak counts once however many of its bins + are called, so precision starts at positive bins / bins (P/N) and falls to M/(M+Q) as peaks + saturate (M peaks, Q negative bins). + + After k randomly ranked bins (drawn without replacement), a peak of s bins is hit with probability + 1 - C(N-s, k)/C(N, k), so E[TP_k] = sum over peaks of that, and E[FP_k] = k*Q/N. + + :param y_member: member array from peak_gs_array_to_member_array (peak ids > 0, negative bins < 0) + :param n_points: number of k values, geometrically spaced from 1 to N + :return: DataFrame with 'Precision' and 'Recall' columns in increasing recall, None when there are no peaks + """ + y_member = np.asarray(y_member) + n_bins = len(y_member) + n_negative = np.count_nonzero(y_member < 0) + + _, peak_sizes = np.unique(y_member[y_member > 0], return_counts=True) + n_peaks = len(peak_sizes) + if n_peaks == 0: + return None + + # Peaks of the same size share the same hit probability + sizes, size_counts = np.unique(peak_sizes, return_counts=True) + + k = np.unique(np.geomspace(1, n_bins, n_points).astype(int)).astype(float) + + # log C(N-s, k) - log C(N, k); a peak is certainly hit once k > N - s + remaining = n_bins - sizes[:, None] - k[None, :] + log_miss = (special.gammaln(n_bins - sizes[:, None] + 1) - special.gammaln(np.maximum(remaining, 0) + 1) + - special.gammaln(n_bins + 1) + special.gammaln(n_bins - k[None, :] + 1)) + miss = np.where(remaining >= 0, np.exp(log_miss), 0.0) + + expected_tp = (size_counts[:, None] * (1 - miss)).sum(axis=0) + expected_fp = k * n_negative / n_bins + + return pd.DataFrame({'Precision': expected_tp / (expected_tp + expected_fp), + 'Recall': expected_tp / n_peaks}) + +def random_aup_ucper(y_member, n_points=2000): + """ + Expected AUP-UCPeR of a random ranking: the area under random_ucper_curve. + + :return: random AUP-UCPeR, NaN when there are no peaks + """ + curve = random_ucper_curve(y_member, n_points) + if curve is None: + return np.nan + + return metrics.auc(x=curve['Recall'], y=curve['Precision']) + +def random_precision_at_ucper(y_member, percent_recall, n_points=2000): + """ + Expected precision of a random ranking at a given unique-peak recall, read off random_ucper_curve + with the same interpolation as Precision_for_Recall. + + :return: random precision at percent_recall, NaN when there are no peaks + """ + curve = random_ucper_curve(y_member, n_points) + if curve is None: + return np.nan + + return Precision_for_Recall(curve, percent_recall) + class ChromosomeAUPRC(object): """ Benchmark maxATAC binary predictions against a gold standard using AUPRC. @@ -455,7 +537,8 @@ def __init__(self, plot=False, peak_based=False, alternative_prediction_bw=None, - prediction_combine_operation="mean" + prediction_combine_operation="mean", + random_only=False ): """ :param prediction_bw: Path to bigwig file containing maxATAC predictions @@ -464,11 +547,16 @@ def __init__(self, :param chromosome: Chromosome to benchmark :param bin_size: Resolution to bin the results to :param agg_function: Method to use to aggregate multiple signals in the same bin + :param random_only: With peak_based, only write the random AUP-UCPeR and P@10%UCPeR; the prediction is not read """ + if random_only and not peak_based: + raise ValueError("random_only requires peak_based") + self.results_location = results_location - self.prediction_stream = load_bigwig(prediction_bw) - self.alternative_prediction_stream = load_bigwig(alternative_prediction_bw) if alternative_prediction_bw else None + if not random_only: + self.prediction_stream = load_bigwig(prediction_bw) + self.alternative_prediction_stream = load_bigwig(alternative_prediction_bw) if alternative_prediction_bw else None self.goldstandard_stream = load_bigwig(goldstandard_bw) self.chromosome = chromosome @@ -496,6 +584,12 @@ def __init__(self, ) self.peak_based=peak_based + + if random_only: + self.__import_goldstandard_array__() + self.__random_UCPeR__() + return + self.__import_prediction_array__(round_prediction=round_predictions) self.__import_goldstandard_array__() self.__AUPRC__() @@ -504,6 +598,19 @@ def __init__(self, logging.info("Plotting AUPRC Curves") self.__plot() + def __random_UCPeR__(self): + """ + Write only the random baselines of the peak-based benchmark: Random AUP-UCPeR and Random P@10%UCPeR. + Both depend on the gold standard, bin size and mask alone, so no prediction is needed. + """ + logging.info("Calculate random AUP-UCPeR and P@10%UCPeR for " + self.chromosome) + + member_array = peak_gs_array_to_member_array(self.goldstandard_array[self.blacklist_mask]) + + pd.DataFrame({'Random_AUPRC': [random_aup_ucper(member_array)], + 'Random_Precision_at_10_Percent_Recall': [random_precision_at_ucper(member_array, 0.1)]} + ).to_csv(self.results_location, sep='\t', index=False) + def __import_prediction_array__(self, round_prediction=6): """ Import the chromosome signal from the predictions bigwig file and convert to a numpy array. @@ -524,8 +631,10 @@ def __import_prediction_array__(self, round_prediction=6): combine_operation=self.prediction_combine_operation) # Under "sum" the bin value is a base-pair total; divide by bin_size to stay on the - # same per-base scale as max/mean. - if self.agg_function == "sum": + # same per-base scale as max/mean. rank_max is already a percentile, and dividing it would let + # the rounding below merge neighbouring ranks into ties + if self.agg_function == "sum" and not (self.alternative_prediction_stream is not None + and self.prediction_combine_operation == "rank_max"): self.prediction_array = self.prediction_array / self.bin_size self.prediction_array = np.round(self.prediction_array, round_prediction) @@ -560,7 +669,7 @@ def __import_goldstandard_array__(self): self.goldstandard_array = self.goldstandard_array > 0 self.random_precision = np.count_nonzero(self.goldstandard_array[self.blacklist_mask]) / \ - np.size(self.prediction_array[self.blacklist_mask]) + np.count_nonzero(self.blacklist_mask) def __get_true_positives__(self, threshold): """ @@ -635,8 +744,9 @@ def __AUPRC__(self): ) else: # generate member array from gs + member_array = peak_gs_array_to_member_array(self.goldstandard_array[self.blacklist_mask]) self.precision, self.recall, self.thresholds = precision_recall_curve_peak_based( - peak_gs_array_to_member_array(self.goldstandard_array[self.blacklist_mask]), + member_array, self.prediction_array[self.blacklist_mask] ) logging.info("Making DataFrame from results") @@ -657,23 +767,38 @@ def __AUPRC__(self): self.PR_CURVE_DF["AUPRC"] = self.AUPRC if self.peak_based==False: - # Calculate the total gold standard bins + # Count gold standard bins with the same mask as the PR curve (blacklist removed, whitelist applied). + # Counting them chromosome wide while dividing by the evaluated bins inflates the random baseline, + # above 1 with a small whitelist logging.info("Calculate Total GoldStandard Bins") - self.PR_CURVE_DF["Total_GoldStandard_Bins"] = len(np.argwhere(self.goldstandard_array == True)) - - # Find the number of non-blacklisted bins in chr of interest - rand_bins = len(np.argwhere(self.blacklist_mask == True)) + self.PR_CURVE_DF["Total_GoldStandard_Bins"] = np.count_nonzero(self.goldstandard_array[self.blacklist_mask]) - # Random Precision - self.PR_CURVE_DF['Random_AUPRC'] = self.PR_CURVE_DF['Total_GoldStandard_Bins'] / rand_bins + # Random Precision: gold standard bins / evaluated bins, i.e. self.random_precision + self.PR_CURVE_DF['Random_AUPRC'] = self.random_precision # Log2FC self.PR_CURVE_DF['log2FC_AUPRC_Random_AUPRC'] = np.log2(self.PR_CURVE_DF["AUPRC"] / self.PR_CURVE_DF["Random_AUPRC"]) + else: + # Peaks and bins counted with the same mask as the AUP-UCPeR curve + self.PR_CURVE_DF["Total_GoldStandard_Bins"] = np.count_nonzero(member_array > 0) + self.PR_CURVE_DF["Total_GoldStandard_Peaks"] = len(np.unique(member_array[member_array > 0])) + + # Random AUP-UCPeR: area under the expected random curve, not the flat bin-level ratio + self.PR_CURVE_DF['Random_AUPRC'] = random_aup_ucper(member_array) + + self.PR_CURVE_DF['log2FC_AUPRC_Random_AUPRC'] = np.log2(self.PR_CURVE_DF["AUPRC"] / self.PR_CURVE_DF["Random_AUPRC"]) # Precision at 10% Recall self.PR_CURVE_DF['Precision_at_10_Percent_Recall']=Precision_for_Recall(self.PR_CURVE_DF, 0.1) + if self.peak_based: + # Random P@10%UCPeR: the expected random curve read at 10% unique-peak recall + self.PR_CURVE_DF['Random_Precision_at_10_Percent_Recall'] = random_precision_at_ucper(member_array, 0.1) + + self.PR_CURVE_DF['log2FC_Precision_at_10_Percent_Recall_Random'] = np.log2( + self.PR_CURVE_DF['Precision_at_10_Percent_Recall'] / self.PR_CURVE_DF['Random_Precision_at_10_Percent_Recall']) + logging.info("Write results for " + self.chromosome) # Write the AUPRC stats to a dataframe diff --git a/maxatac/utilities/callbacks.py b/maxatac/utilities/callbacks.py index ee8db87..7ce6723 100644 --- a/maxatac/utilities/callbacks.py +++ b/maxatac/utilities/callbacks.py @@ -1,5 +1,7 @@ from tensorflow.keras.callbacks import ModelCheckpoint, CSVLogger, TensorBoard -from .batch_logger import BatchLossLogger # import your custom logger +import os + +from .batch_logger import BatchLossLogger def get_callbacks(model_location, log_location, @@ -10,7 +12,7 @@ def get_callbacks(model_location, append_log=False, tensor_board_write_images=False, tensor_board_write_graph=True, - batch_log_location=False, # new argument + batch_log_location=False, # True: also write a per-batch loss log next to log_location ): callbacks = [ ModelCheckpoint(filepath=model_location, @@ -27,9 +29,9 @@ def get_callbacks(model_location, ] if batch_log_location: - list = log_location.split("/")[:-1] - list.append('ELK1_quant_batch_log.csv') - batch_log_location = "/".join(list) + # Name the batch log after the run's epoch log, e.g. .csv -> _batch.csv + stem, ext = os.path.splitext(log_location) + batch_log_location = stem + "_batch" + (ext or ".csv") callbacks.append(BatchLossLogger(batch_log_location)) return callbacks diff --git a/maxatac/utilities/constants.py b/maxatac/utilities/constants.py index aecdaac..d5f334d 100644 --- a/maxatac/utilities/constants.py +++ b/maxatac/utilities/constants.py @@ -22,6 +22,13 @@ # build maxatac data path maxatac_data_path = os.path.join(os.path.expanduser('~'), "opt", "maxatac", "data") +# Reference data + quant-maxATAC models installed by `maxatac data`. It replaces MiraldiLab/maxATAC_data, +# which holds the binary maxATAC v1 models. +MAXATAC_DATA_REPO = "https://github.com/MiraldiLab/quant-maxATAC_data.git" + +# Where users can ask for the maxATAC v1 (binary) models to be supported again +V1_MODELS_WISHLIST_URL = "https://github.com/MiraldiLab/quant-maxATAC/issues" + # build processing script path names prepare_atac_script_dir = os.path.join(maxatac_data_path, "scripts", "ATAC", "ATAC_bowtie2_pipeline.sh") # bulk processing script @@ -62,12 +69,20 @@ "chr18", "chr20", "chr21", "chr22"] DEFAULT_VALIDATE_CHRS = ["chr2", "chr19"] +# maxatac threshold calibrates on exactly one held-out chromosome +DEFAULT_THRESHOLD_CHR = "chr2" + +# maxatac predict: upper bound on chromosomes predicted in parallel (one model + genome per process) +DEFAULT_PREDICT_THREADS = 24 DEFAULT_TEST_CHRS = ["chr1", "chr8"] DEFAULT_LOG_LEVEL = "info" -DEFAULT_TRAIN_EPOCHS = 20 +DEFAULT_TRAIN_EPOCHS = 100 + +# Number of pyBigWig zoom levels written to output bigWig files (0-10) +DEFAULT_MAX_ZOOMS = 10 DEFAULT_TRAIN_BATCHES_PER_EPOCH = 100 @@ -94,6 +109,11 @@ DNA_INPUT_CHANNELS = 4 DILATION_RATE = [1, 1, 2, 4, 8, 16] BP_RESOLUTION = 32 + +# Binary-model training target: a 32 bp bin is labelled bound (1) when more than this fraction +# of its bases fall inside a ChIP-seq peak in Binding_File (maxATAC v1 rule; Binding_File must be +# a 0/1 peak track for this to mean 'fraction of bases'). Quant models ignore it and use the bin mean. +BINARY_TARGET_MIN_PEAK_FRACTION = 0.5 OUTPUT_FILTERS = 1 OUTPUT_KERNEL_SIZE = 1 POOL_SIZE = 2 diff --git a/maxatac/utilities/genome_tools.py b/maxatac/utilities/genome_tools.py index f8533e9..84eeac5 100644 --- a/maxatac/utilities/genome_tools.py +++ b/maxatac/utilities/genome_tools.py @@ -1,5 +1,7 @@ +import logging import pandas as pd import numpy as np +from scipy.stats import rankdata import pyBigWig import py2bit import random @@ -126,78 +128,6 @@ def get_bigwig_stats(bigwig_path, chrom_name, chrom_end, bin_count, agg_function )) -def get_target_matrix(binding, - chromosome, - start, - end, - bp_resolution): - """ - Get the values from a ChIP-seq signal file - - :param binding: ChIP-seq signal file - :param chromosome: chromosome name: chr1 - :param start: start - :param end: end - :param bp_resolution: Prediction resolution in base pairs - - :return: Returns a vector of binary values - """ - target_vector = np.array(binding.values(chromosome, start, end)).T - - target_vector = np.nan_to_num(target_vector, 0.0) - - n_bins = int(target_vector.shape[0] / bp_resolution) - - split_targets = np.array(np.split(target_vector, n_bins, axis=0)) - - bin_sums = np.sum(split_targets, axis=1) - - return np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) - # TODO play with this parameter of 0.5 - - -def get_synced_chroms(chroms, ignore_regions=None): - """ - This function will generate a nested dictionary of chromosome sizes and the regions available for training. - - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - - If ignore_regions is True, set regions to the whole chromosome length - Returns something like this - - """ - chroms_and_regions = {} - for chrom in chroms: - chrom_name, *region = chrom.replace(",", "").split(":") # region is either [] or ["start-end", ...] - chroms_and_regions[chrom_name] = None - if not ignore_regions: - try: - chroms_and_regions[chrom_name] = [int(i) for i in region[0].split("-")] - except (IndexError, ValueError): - pass - - loaded_chroms = set() - - synced_chroms = {} - for chrom_name, chrom_length in loaded_chroms: - if chrom_name not in chroms_and_regions: continue - region = chroms_and_regions[chrom_name] - if not region or \ - region[0] < 0 or \ - region[1] <= 0 or \ - region[0] >= region[1] or \ - region[1] > chrom_length: - region = [0, chrom_length] - synced_chroms[chrom_name] = { - "length": chrom_length, - "region": region - } - return synced_chroms - - class EmptyStream(): def __enter__(self): return None @@ -286,13 +216,51 @@ def import_bigwig_stats_array(bigwig_stream, chromosome, chromosome_length, agg_ dtype=float) +def _pct_rank(array): + """ + Percentile rank of each bin across the whole array: rankdata(method="min") / number of bins. + NaN (missing) bins are set to 0 first, and every zero-valued bin gets percentile 0, so the + many zero bins of a sparse track cannot outrank low but nonzero bins of the other track. + """ + array = np.nan_to_num(np.asarray(array, dtype=float)) + if array.size == 0: + return array + + percentile = rankdata(array, method="min") / array.size + percentile[array == 0] = 0.0 + + return percentile + + +def _log_max_source(primary_array, alternative_array, combine_operation): + """ + Sanity check for a max combine: how often each track supplies the max. Near 0% or 100% means + the ensemble is effectively just one of the two inputs. + """ + n_bins = primary_array.size + if n_bins == 0: + return + + primary_wins = np.count_nonzero(primary_array > alternative_array) / n_bins + alternative_wins = np.count_nonzero(alternative_array > primary_array) / n_bins + + logging.info("%s combine: primary supplies the max in %.2f%% of bins, alternative in %.2f%%, tied in %.2f%%", + combine_operation, 100 * primary_wins, 100 * alternative_wins, + 100 * (1 - primary_wins - alternative_wins)) + + def combine_prediction_arrays(primary_array, alternative_array=None, combine_operation="mean"): """ Combine two prediction arrays element-wise. - Whenever both arrays contain values for the same bin, combine them using either the + mean / max: whenever both arrays contain values for the same bin, combine them using either the element-wise mean or max. If only one array has a value for a bin, use the available value. If neither has a value, return 0 for that position. + + rank_max: convert each array to percentile ranks across all of its bins (_pct_rank), then take the + element-wise max. Missing bins get percentile 0, so the other track's value is used, which is the + same missing-value rule as max. Rank before any masking: the result does not depend on the + blacklist or whitelist. """ primary_array = np.array(primary_array, dtype=float) if alternative_array is None: @@ -303,8 +271,15 @@ def combine_prediction_arrays(primary_array, alternative_array=None, combine_ope if primary_array.shape != alternative_array.shape: raise ValueError("Prediction arrays must have the same shape to be combined.") - if combine_operation not in {"mean", "max"}: - raise ValueError("combine_operation must be either 'mean' or 'max'.") + if combine_operation not in {"mean", "max", "rank_max"}: + raise ValueError("combine_operation must be one of 'mean', 'max' or 'rank_max'.") + + if combine_operation == "rank_max": + primary_percentile = _pct_rank(primary_array) + alternative_percentile = _pct_rank(alternative_array) + _log_max_source(primary_percentile, alternative_percentile, combine_operation) + + return np.maximum(primary_percentile, alternative_percentile) primary_available = ~np.isnan(primary_array) alternative_available = ~np.isnan(alternative_array) @@ -318,6 +293,8 @@ def combine_prediction_arrays(primary_array, alternative_array=None, combine_ope combined[both_available] = (primary_array[both_available] + alternative_array[both_available]) / 2.0 else: combined[both_available] = np.maximum(primary_array[both_available], alternative_array[both_available]) + _log_max_source(np.nan_to_num(primary_array, nan=-np.inf), np.nan_to_num(alternative_array, nan=-np.inf), + combine_operation) return np.nan_to_num(combined) diff --git a/maxatac/utilities/losses.py b/maxatac/utilities/losses.py index ebd435e..2298cb2 100644 --- a/maxatac/utilities/losses.py +++ b/maxatac/utilities/losses.py @@ -1,4 +1,4 @@ -import pandas as pd +import logging from maxatac.utilities.system_tools import Mute import tensorflow as tf @@ -88,7 +88,7 @@ def __init__(self, name="pearsonr_mse", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.001 #best def call(self, y_true, y_pred): #multinomial part of loss function @@ -104,7 +104,7 @@ def __init__(self, name="pearsonr_poisson", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.1 ###TODO: SET TO 0.001 def call(self, y_true, y_pred): #multinomial part of loss function @@ -129,7 +129,6 @@ def __init__(self, name="mse", **kwargs): super().__init__(name=name) def call(self, y_true, y_pred): - print("value: ", tf.keras.losses.MSE(y_true,y_pred)) return tf.keras.losses.MSE(y_true,y_pred) class multinomialnll(tf.keras.losses.Loss): @@ -140,11 +139,11 @@ def call(self, y_true, y_pred): logits_perm = y_pred true_counts_perm = y_true - #import numpy - #np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/true_counts_perm.tsv", true_counts_perm, delimiter='\t') - #np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/logits_perm.tsv", logits_perm, delimiter='\t') - - import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + try: + import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + except ImportError as err: + raise ImportError("The multinomial losses need tensorflow-probability: " + "pip install 'maxatac[multinomial]'") from err counts_per_example = tf.reduce_sum(true_counts_perm, axis=-1) dist = tfp.distributions.Multinomial(total_count=counts_per_example, @@ -161,9 +160,8 @@ def __init__(self, name="multinomialnll_mse", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.0000001 - self.counter=1 def call(self, y_true, y_pred): # GOPHER implementation of loss @@ -176,7 +174,11 @@ def call(self, y_true, y_pred): true_counts_perm = y_true - import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + try: + import tensorflow_probability as tfp # optional dependency, only needed for multinomial losses + except ImportError as err: + raise ImportError("The multinomial losses need tensorflow-probability: " + "pip install 'maxatac[multinomial]'") from err counts_per_example = tf.reduce_sum(true_counts_perm, axis=-1) dist = tfp.distributions.Multinomial(total_count=counts_per_example, @@ -221,13 +223,6 @@ def call(self, y_true, y_pred): # multinomial loss multinomial_loss = multinomialnll()(y_true, logits) - ''' - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_true.tsv", y_true, - delimiter='\t') - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_pred.tsv", y_pred, - delimiter='\t') - ''' - MSE_loss = tf.keras.losses.MSE([K.log(1 + K.sum(y_true, axis=(-2, -1)))], [K.log(1 + K.sum(y_pred, axis=(-2, -1)))]) @@ -236,27 +231,6 @@ def call(self, y_true, y_pred): total_loss = bpnet_loss - ''' - if self.counter in range(0,40): - epoch = 1 - elif self.counter in range(40,80): - epoch = 2 - elif self.counter in range(80,120): - epoch = 3 - elif self.counter in range(120,160): - epoch = 4 - else: - epoch = 5 - - tf.print("epoch: ", epoch, "multinomialnll_GOPHER: ", total_loss, "multinomialnll_BPnet: ", bpnet_loss) - self.counter = self.counter +1 - - if self.counter == 39 or self.counter ==79 or self.counter == 119 or self.counter == 159 or self.counter==199: - - df=pd.DataFrame([[total_loss.numpy(), bpnet_loss.numpy()]], columns=['GOPHER_multinomialnll', 'BPnet_multinomialnll']) - - df.to_csv("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/Epoch_"+str(epoch)+"_loss_comp.tsv", sep = '\t')''' - return total_loss class multinomialnll_mse_bpnet(tf.keras.losses.Loss): @@ -264,7 +238,7 @@ def __init__(self, name="multinomialnll_mse_bpnet", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.0000001 def call(self, y_true, y_pred): @@ -276,11 +250,6 @@ def call(self, y_true, y_pred): # multinomial loss multinomial_loss = multinomialnll()(y_true, logits) - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_true.tsv", y_true, - delimiter='\t') - np.savetxt("/Users/war9qi/Project_Data/maxATAC_sample/ELK1_quantitative_output/y_pred.tsv", y_pred, - delimiter='\t') - mse_loss = tf.keras.losses.MSE([K.log(1 + K.sum(y_true, axis=(-2, -1)))], [K.log(1 + K.sum(y_pred, axis=(-2, -1)))]) @@ -293,7 +262,7 @@ def __init__(self, name="multinomialnll_mse_reg", **kwargs): super().__init__(name=name) self.alpha = kwargs.get('loss_params') if not self.alpha: - print('ALPHA SET TO DEFAULT VALUE!') + logging.info('loss_params not provided, using the default alpha') self.alpha = 0.0000001 # self.alpha=0.001 def call(self, y_true, y_pred): @@ -347,16 +316,8 @@ def __init__(self, name="r2", **kwargs): super().__init__(name=name) def call(self, y_true, y_pred): - print(y_true) - print(y_pred) y_true = tf.cast(y_true, 'float32') y_pred = tf.cast(y_pred, 'float32') - print("y_true shape") - print(y_true.shape) - print(y_true) - print("y_pred shape") - print(y_pred.shape) - print(y_pred) shape = y_true.shape[-1] true_sum = tf.reduce_sum(y_true, axis=[0,1]) @@ -367,18 +328,14 @@ def call(self, y_true, y_pred): count = tf.reduce_sum(count, axis=[0,1]) true_mean = tf.divide(true_sum, count) - print(true_mean) true_mean2 = tf.math.square(true_mean) - print(true_mean2) total = true_sumsq - tf.multiply(count, true_mean2) - print(total) resid1 = pred_sumsq resid2 = -2*product resid3 = true_sumsq resid = resid1 + resid2 + resid3 - print(resid) r2 = tf.ones_like(shape, dtype=tf.float32) - tf.divide(resid, total) return -tf.reduce_mean(r2) @@ -406,34 +363,31 @@ def __init__(self, name="kl_divergence", **kwargs): super().__init__(name=name) def call(self, y_true, y_pred): - from sklearn.preprocessing import normalize - - # KLD call - - '''loss = tf.keras.losses.KLDivergence().call(y_true=tf.linalg.normalize(y_true, ord=1, axis=1)[0], - y_pred=tf.linalg.normalize(y_pred, ord=1, axis=1)[0])''' - + """ + KL(p || q) = sum_i p_i * (log p_i - log q_i), with p = y_true and q = y_pred each + L1-normalized along the output axis so every example is treated as a distribution + over bins. Averaged over the batch. + """ epsilon = 1e-8 - y_true = tf.where(tf.math.is_nan(y_true), epsilon * tf.ones_like(y_true), y_true) - y_pred = tf.where(tf.math.is_nan(y_pred), epsilon * tf.ones_like(y_pred), y_pred) - - y_true = tf.where(tf.math.is_inf(y_true), epsilon * tf.ones_like(y_true), y_true) - y_pred = tf.where(tf.math.is_inf(y_pred), epsilon * tf.ones_like(y_pred), y_pred) - - y_true = tf.clip_by_value(y_true, epsilon, 1.0) - y_pred = tf.clip_by_value(y_pred, epsilon, 1.0) - - y_true_normalized = tf.linalg.normalize(y_true, ord=1, axis=1)[0] - y_pred_normalized = tf.linalg.normalize(y_pred, ord=1, axis=1)[0] + y_true = tf.cast(y_true, 'float32') + y_pred = tf.cast(y_pred, 'float32') + # Replace NaN/inf and keep the inputs strictly positive before normalizing. No upper + # clip here: quantitative targets are unbounded signal, not probabilities. + y_true = tf.where(tf.math.is_finite(y_true), y_true, epsilon * tf.ones_like(y_true)) + y_pred = tf.where(tf.math.is_finite(y_pred), y_pred, epsilon * tf.ones_like(y_pred)) + y_true = tf.maximum(y_true, epsilon) + y_pred = tf.maximum(y_pred, epsilon) - log_y_pred = tf.math.log(y_pred_normalized) + p = tf.linalg.normalize(y_true, ord=1, axis=1)[0] + q = tf.linalg.normalize(y_pred, ord=1, axis=1)[0] - # Compute the KL divergence manually - loss = tf.reduce_sum(y_true_normalized * log_y_pred, axis=1) + p = tf.clip_by_value(p, epsilon, 1.0) + q = tf.clip_by_value(q, epsilon, 1.0) + kl = tf.reduce_sum(p * (tf.math.log(p) - tf.math.log(q)), axis=1) - return loss + return tf.reduce_mean(kl) class cauchy_lf(tf.keras.losses.Loss): def __init__(self, name="cauchy_lf", **kwargs): diff --git a/maxatac/utilities/normalization_tools.py b/maxatac/utilities/normalization_tools.py index 94000a8..d1deba8 100644 --- a/maxatac/utilities/normalization_tools.py +++ b/maxatac/utilities/normalization_tools.py @@ -52,11 +52,14 @@ def get_genomic_stats(bigwig_path: str, chrom_sizes_dict[chromosome] ) - # Append minmax results to list + # Per-chromosome stats over non-blacklisted bases; median is of the non-zero signal, + # matching the genome-wide median below, and 0 for a chromosome with no signal at all + chr_vals_masked = chr_vals[blacklist_mask] + chr_nonzero = chr_vals_masked[chr_vals_masked > 0] minmax_results.append([chromosome, - np.min(chr_vals[blacklist_mask]), - np.max(chr_vals[blacklist_mask]), - np.median(chr_vals[blacklist_mask] > 0) + np.min(chr_vals_masked), + np.max(chr_vals_masked), + np.median(chr_nonzero) if chr_nonzero.size else 0.0 ]) # Append chrom values to an array with genome-wide values @@ -143,16 +146,6 @@ def arcsinh_normalize_array(array): """ return np.arcsinh(array) -def log2_normalize_array(array): - """ - log2() normalize the numpy array - - :param array: Input array of bigwig values - - :return: log2 normalized array - """ - return np.log2(array) + 1 - def log1p_normalize_array(array): """ log1p()normalize the numpy array diff --git a/maxatac/utilities/parser.py b/maxatac/utilities/parser.py index 1b92797..0f8153f 100644 --- a/maxatac/utilities/parser.py +++ b/maxatac/utilities/parser.py @@ -27,12 +27,15 @@ LOG_LEVELS, DEFAULT_LOG_LEVEL, DEFAULT_TRAIN_EPOCHS, + DEFAULT_MAX_ZOOMS, DEFAULT_TRAIN_BATCHES_PER_EPOCH, BATCH_SIZE, VAL_BATCH_SIZE, INPUT_LENGTH, DEFAULT_TRAIN_CHRS, DEFAULT_VALIDATE_CHRS, + DEFAULT_THRESHOLD_CHR, + DEFAULT_PREDICT_THREADS, DEFAULT_ROUND, DEFAULT_TEST_CHRS, DEFAULT_BENCHMARKING_AGGREGATION_FUNCTION, @@ -45,7 +48,8 @@ BINARY_LOSS, QUANT_LOSS, QUANT_LOSSES, - QUANT_TARGET_SCALE_FACTOR + QUANT_TARGET_SCALE_FACTOR, + MAXATAC_DATA_REPO ) @@ -103,7 +107,8 @@ def get_parser(): type=str, default="hg38", required=False, - help="The reference genome build to use." + help="The reference genome build to use. Can be given before or after the subcommand. " + "Default: hg38" ) ############################################# @@ -135,6 +140,34 @@ def get_parser(): help="Output results directory." ) + data_parser.add_argument("--data_repo", + dest="data_repo", + type=str, + default=MAXATAC_DATA_REPO, + required=False, + help="Git repository to install the reference data and models from. " + "Default: " + MAXATAC_DATA_REPO + ) + + data_parser.add_argument("--data_version", + dest="data_version", + type=str, + default=None, + required=False, + help="Tag or branch of the data repository to install (e.g. v2.0.0b1), or 'latest' " + "for the newest commit on its default branch. Default: the tag matching this " + "quant-maxATAC version (" + get_version() + "); development versions and " + "versions without a matching tag install the latest data." + ) + + data_parser.add_argument("-y", "--yes", + dest="yes", + action="store_true", + default=False, + help="Overwrite an existing data directory, including any maxATAC v1 models, " + "without asking for confirmation." + ) + data_parser.add_argument("--loglevel", dest="loglevel", type=str, @@ -181,10 +214,11 @@ def get_parser(): # Add optional arguments to the parser + # dest must be chrom_sizes: update_reference_genome_paths fills that attribute from --genome when unset average_parser.add_argument("-cs", "--chrom_sizes", "--chromosome_sizes", - dest="chromosome_sizes", + dest="chrom_sizes", type=str, - help="Input chromosome sizes file" + help="Input chromosome sizes file. Default: the chromosome sizes of --genome" ) average_parser.add_argument("-c", "--chroms", "--chromosomes", @@ -195,6 +229,23 @@ def get_parser(): help="Chromosomes for averaging. Default: 1-22" ) + average_parser.add_argument("--genome", + dest="genome", + type=str, + default=argparse.SUPPRESS, + required=False, + help="The reference genome build to which the input file was aligned." + ) + + average_parser.add_argument("--max_zooms", + dest="max_zooms", + type=int, + default=DEFAULT_MAX_ZOOMS, + required=False, + help="The number of zoom levels that should be computed for the averaged bigWig file. " + "Default: " + str(DEFAULT_MAX_ZOOMS) + ) + average_parser.add_argument("-o", "--output", "--output_dir", dest="output_dir", type=str, @@ -257,6 +308,23 @@ def get_parser(): type=str, help="Genome sequence 2bit file." ) + + predict_parser.add_argument("--genome", + dest="genome", + type=str, + default=argparse.SUPPRESS, + required=False, + help="The reference genome build to which the input file was aligned." + ) + + predict_parser.add_argument("--max_zooms", + dest="max_zooms", + type=int, + default=DEFAULT_MAX_ZOOMS, + required=False, + help="The number of zoom levels that should be computed for the output bigWig file. " + "Default: " + str(DEFAULT_MAX_ZOOMS) + ) predict_parser.add_argument("-i", "-s", "--signal", dest="signal", @@ -361,9 +429,10 @@ def get_parser(): dest="cutoff_type", default="F1", type=str, - choices=["Precision", "Recall", "F1"], + choices=["Precision", "Recall", "F1", "Peak_Recall"], help="Metric whose calibration grid is used to pick the peak calling \ - threshold. Default: F1" + threshold. Peak_Recall is the fraction of unique ChIP-seq peaks \ + recovered. Default: F1" ) predict_parser.add_argument("-cv", "-cutoff_value", "--cutoff_value", @@ -390,6 +459,16 @@ def get_parser(): required=False, help="Skip calling peaks on prediction tracks" ) + + predict_parser.add_argument("--threads", + dest="threads", + type=int, + default=DEFAULT_PREDICT_THREADS, + help="Maximum number of chromosomes to predict in parallel. Each process loads " + "the full model and genome, so lower this if you run out of memory. " + "Capped by the number of chromosomes and available CPUs. Default: " + + str(DEFAULT_PREDICT_THREADS) + ) ############################################# # Train parser @@ -435,9 +514,9 @@ def get_parser(): train_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, - help="The reference genome build to use." + help="The reference genome build to which the input file was aligned." ) train_parser.add_argument("--sequence", @@ -673,35 +752,43 @@ def get_parser(): type=str, required=True, help="Input .bigwig file." - ) + ) normalize_parser.add_argument("-n", "--name", "--prefix", required=True, dest="name", type=str, help="Name to use for filename" - ) + ) normalize_parser.add_argument("-cs", "--chrom_sizes", "--chromosome_sizes", dest="chrom_sizes", type=str, help="Chrom sizes file" - ) + ) normalize_parser.add_argument("-c", "--chroms", "--chromosomes", dest="chromosomes", type=str, nargs="+", default=AUTOSOMAL_CHRS, - help="Chromosomes for normalization. Default: 1-22" + help="Chromosomes for normalization. Default: 1-22 from the hg38 genome" ) + normalize_parser.add_argument("--genome", + dest="genome", + type=str, + default=argparse.SUPPRESS, + required=False, + help="The reference genome build to use." + ) + normalize_parser.add_argument("-o", "--output", "--output_dir", dest="output_dir", type=str, default=os.getcwd(), help="Output directory. Default: Output to current working directory." - ) + ) normalize_parser.add_argument("--min", dest="min", @@ -709,7 +796,7 @@ def get_parser(): type=int, default=0, help="The minimum value to use for normalization" - ) + ) normalize_parser.add_argument("--max", dest="max", @@ -717,7 +804,7 @@ def get_parser(): required=False, default=False, help="The maximum value to use for normalization" - ) + ) normalize_parser.add_argument("--clip", dest="clip", @@ -730,20 +817,29 @@ def get_parser(): dest="method", type=str, default="min-max", - choices=["min-max", "zscore", "arcsinh", "log2", "log1p", "sqrt", + choices=["min-max", "zscore", "arcsinh", "log1p", "sqrt", "three_fourths", "three_eighths"], help="The method to use for normalization. min-max is the ATAC-seq input " "normalization used by maxATAC; the variance-stabilizing transforms " - "(arcsinh, log2, log1p, sqrt, three_fourths, three_eighths) are provided " + "(arcsinh, log1p, sqrt, three_fourths, three_eighths) are provided " "for preparing quantitative ChIP-seq target tracks. Default: min-max" ) + normalize_parser.add_argument("--max_zooms", + dest="max_zooms", + type=int, + default=DEFAULT_MAX_ZOOMS, + required=False, + help="The number of zoom levels that should be computed for the normalized bigWig file. " + "Default: " + str(DEFAULT_MAX_ZOOMS) + ) + normalize_parser.add_argument("--max_percentile", dest="max_percentile", type=int, default=99, help="The maximum percentile to use for normalization" - ) + ) normalize_parser.add_argument("--loglevel", dest="loglevel", @@ -751,13 +847,13 @@ def get_parser(): default="info", choices=LOG_LEVELS.keys(), help="Logging level. Default: " + DEFAULT_LOG_LEVEL - ) + ) normalize_parser.add_argument("--blacklist_bw", dest="blacklist_bw", type=str, help="The blacklisted regions to exclude (BigWig file format)" - ) + ) ############################################# # Benchmark subparser @@ -772,7 +868,8 @@ def get_parser(): # Add arguments to the parser # Add arguments to the parser - benchmark_prediction_filetype = benchmark_parser.add_mutually_exclusive_group(required=True) + # Required unless --random (checked in parse_arguments): the random baselines do not read the prediction + benchmark_prediction_filetype = benchmark_parser.add_mutually_exclusive_group(required=False) benchmark_prediction_filetype.add_argument("-bed", "--bed", dest="prediction", @@ -796,9 +893,12 @@ def get_parser(): benchmark_parser.add_argument("--prediction_combine_operation", dest="prediction_combine_operation", type=str, - choices=["mean", "max"], + choices=["mean", "max", "rank_max"], default="mean", - help="How to combine bins from the primary and alternative prediction bigWig files when both provide a value. Default: mean" + help="How to combine bins from the primary and alternative prediction bigWig files. " + "mean / max combine raw values where both provide one. rank_max converts each " + "track to per-chromosome percentile ranks (zero and missing bins get 0) and " + "takes the max; precision-recall benchmark only, not with --quant. Default: mean" ) benchmark_parser.add_argument("--quant_gold_standard", @@ -834,6 +934,16 @@ def get_parser(): "Binary benchmark only." ) + benchmark_parser.add_argument("--random", + dest="random", + action='store_true', + default=False, + help="With --peak_based, compute only the random baselines, Random AUP-UCPeR and " + "Random P@10%%UCPeR, from the gold standard, bin size and blacklist/whitelist. " + "The prediction is not read, so --bw/--bed is optional. Writes " + "__bp_random_UCPeR.tsv instead of the PRC file." + ) + benchmark_parser.add_argument("--quant", dest="quant", action='store_true', @@ -881,6 +991,14 @@ def get_parser(): is greater than or equal to this value. Default: " + str(DEFAULT_BENCHMARKING_AGGREGATION_THRESHOLD) ) + benchmark_parser.add_argument("--genome", + dest="genome", + type=str, + default=argparse.SUPPRESS, + required=False, + help="The reference genome build to which the input file was aligned." + ) + benchmark_parser.add_argument("--round_predictions", dest="round_predictions", type=int, @@ -985,9 +1103,10 @@ def get_parser(): dest="cutoff_type", default="F1", type=str, - choices=["Precision", "Recall", "F1"], + choices=["Precision", "Recall", "F1", "Peak_Recall"], help="Metric whose calibration grid is used to pick the peak calling \ - threshold. Default: F1" + threshold. Peak_Recall is the fraction of unique ChIP-seq peaks \ + recovered. Default: F1" ) peaks_parser.add_argument("-cutoff_value", "--cutoff_value", @@ -1065,9 +1184,9 @@ def get_parser(): variants_parser.add_argument("--genome", dest="genome", type=str, - default="hg38", + default=argparse.SUPPRESS, required=False, - help="The reference genome build to use." + help="The reference genome build to which the input file was aligned." ) variants_parser.add_argument("-s", "--sequence", @@ -1195,6 +1314,14 @@ def get_parser(): help="The chromosomes to include in the final output." ) + prepare_parser.add_argument("--genome", + dest="genome", + type=str, + default=argparse.SUPPRESS, + required=False, + help="The reference genome build to which the input file was aligned." + ) + prepare_parser.add_argument("-t", "-threads", "--threads", dest="threads", type=int, @@ -1247,8 +1374,10 @@ def get_parser(): dest="chromosomes", type=str, nargs="+", - default=DEFAULT_VALIDATE_CHRS, - help="Chromosomes used to calibrate thresholds. Default: " + " ".join(DEFAULT_VALIDATE_CHRS) + default=[DEFAULT_THRESHOLD_CHR], + help="The single held-out chromosome used to calibrate thresholds. Exactly one " + "chromosome must be given. Default: " + + DEFAULT_THRESHOLD_CHR ) threshold_parser.add_argument("--bin_size", @@ -1273,12 +1402,27 @@ def get_parser(): choices=LOG_LEVELS.keys(), help="Logging level. Default: " + DEFAULT_LOG_LEVEL ) + + threshold_parser.add_argument("--genome", + dest="genome", + type=str, + default=argparse.SUPPRESS, + required=False, + help="The reference genome build to which the input BAM file was aligned." + ) threshold_parser.add_argument("--blacklist_bw", dest="blacklist_bw", type=str, help="The blacklisted regions to exclude in bigwig format." ) + + threshold_parser.add_argument("--blacklist_bed", + dest="blacklist_bed", + type=str, + help="The blacklisted regions to exclude in BED format. Default: the .bed file " + "next to --blacklist_bw." + ) threshold_parser.add_argument("--meta_file", dest="meta_file", @@ -1286,7 +1430,9 @@ def get_parser(): required=True, help="Tab-separated meta file with one row per cell type and columns 'Prediction' " "(prediction bigWig, quantitative or binary) and 'Binding_File' (binary gold " - "standard bigWig)." + "standard bigWig). Optional column 'ChIP_peaks' (ChIP-seq peak BED) defines the " + "unique peaks for the Peak_Recall (%% of peaks recovered) metric; without it, " + "runs of consecutive gold-standard bins are used." ) return general_parser @@ -1342,6 +1488,25 @@ def parse_arguments(argsl, cwd_abs_path=None): if args.quant and args.loss == BINARY_LOSS: parser.error(f"--loss {BINARY_LOSS} is for binary models; choose one of {', '.join(QUANT_LOSSES)} with --quant") + if args.func == run_thresholding and len(args.chromosomes) != 1: + # parse_known_args would otherwise silently drop the extras with nargs=1 + parser.error("threshold calibrates on exactly one chromosome; got --chromosomes " + + " ".join(args.chromosomes)) + + if args.func == run_benchmarking: + if args.random and not args.peak_based: + parser.error("--random requires --peak_based") + + if args.quant and args.prediction_combine_operation == "rank_max": + parser.error("--prediction_combine_operation rank_max is for the precision-recall benchmark; " + "it cannot be combined with --quant") + + if args.random and args.quant: + parser.error("--random is for the peak-based binary benchmark; it cannot be combined with --quant") + + if not args.random and not args.prediction: + parser.error("one of the arguments -bed/--bed --bw/--bigwig/-bw is required") + if args.func == run_benchmarking and args.quant: missing = [flag for flag, value in (("--quant_gold_standard", args.quant_gold_standard), ("--quant_gs_null", args.quant_gs_null)) if not value] diff --git a/maxatac/utilities/peak_tools.py b/maxatac/utilities/peak_tools.py index 74ca786..e74342e 100644 --- a/maxatac/utilities/peak_tools.py +++ b/maxatac/utilities/peak_tools.py @@ -61,7 +61,7 @@ def call_peaks_per_chromosome(bigwig_path, chrom_name, threshold, bin_size=200): return pd.DataFrame(BIN_list, columns=["chr", "start", "end", "score"]) -CUTOFF_TYPES = ("Precision", "Recall", "F1") +CUTOFF_TYPES = ("Precision", "Recall", "F1", "Peak_Recall") def get_threshold(cutoff_file, cutoff_type, cutoff_val): @@ -70,11 +70,13 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): Args: cutoff_file (str): Threshold calibration table written by `maxatac threshold` (`_cross_celltype.tsv` or a per-sample `.tsv`), with columns - Metric/Bin/Precision/Recall/Threshold/F1. + Metric/Bin/Precision/Recall/Threshold/F1 (+ Peak_Recall). cutoff_type (str): Which metric's bin grid to look the threshold up on. - One of Precision, Recall, F1. - cutoff_val (float): Target value on that metric's grid. Optional for F1, where - omitting it selects the threshold with the highest F1. + One of Precision, Recall, F1, Peak_Recall (fraction of unique ChIP-seq peaks + recovered). + cutoff_val (float): Target value of that metric. The row used must achieve it in its + metric column (not only in its Bin label). Optional for F1, where omitting it + selects the threshold with the highest F1. Returns: float: The threshold to apply to prediction scores. @@ -94,7 +96,9 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): rows = df[df["Metric"] == cutoff_type] if rows.empty: - raise ValueError(f"{cutoff_file} has no {cutoff_type} rows to calibrate a threshold against.") + hint = (" Tables written before Peak_Recall was added lack these rows; regenerate it with " + "`maxatac threshold`.") if cutoff_type == "Peak_Recall" else "" + raise ValueError(f"{cutoff_file} has no {cutoff_type} rows to calibrate a threshold against.{hint}") if cutoff_type == "F1" and cutoff_val is None: selected = rows.loc[rows["F1"].idxmax()] @@ -103,20 +107,25 @@ def get_threshold(cutoff_file, cutoff_type, cutoff_val): if cutoff_val is None: raise ValueError(f"A cutoff value is required for cutoff type {cutoff_type}.") - # Ceiling on the bin grid: the lowest bin that still meets the requested value. - reachable = rows[rows["Bin"] >= cutoff_val].sort_values("Bin") + # The achieved value must meet the request: grid bins past a curve's range hold its + # nearest real row, so the Bin label alone can promise a value no threshold reaches. + reachable = rows[rows[cutoff_type] >= cutoff_val] if reachable.empty: raise ValueError( f"{cutoff_file} does not reach {cutoff_type} {cutoff_val}; " - f"its highest {cutoff_type} bin is {rows['Bin'].max()}." + f"the highest {cutoff_type} it reaches is {rows[cutoff_type].max():.3f}." ) - selected = reachable.iloc[0] + # Closest to the request; ties go to the higher F1 + selected = reachable.sort_values([cutoff_type, "F1"], ascending=[True, False]).iloc[0] + achieved_peak_recall = (f"\n Achieved Peak_Recall: {selected['Peak_Recall']}" + if "Peak_Recall" in selected.index else "") logging.info(f"Threshold calibrated on {cutoff_type} bin {selected['Bin']}: {selected['Threshold']}" + f"\n Achieved Precision: {selected['Precision']}" + f"\n Achieved Recall: {selected['Recall']}" + - f"\n Achieved F1: {selected['F1']}") + f"\n Achieved F1: {selected['F1']}" + + achieved_peak_recall) return float(selected["Threshold"]) diff --git a/maxatac/utilities/plot.py b/maxatac/utilities/plot.py index 809d0f3..ab73f09 100644 --- a/maxatac/utilities/plot.py +++ b/maxatac/utilities/plot.py @@ -20,7 +20,7 @@ def export_model_structure(model, file_location, suffix="_model_structure", ext= def export_binary_metrics(history, tf, RR, ARC, file_location, best_epoch, suffix="_model_dice_acc", ext=".png", - style="seaborn-whitegrid", log_base=10, skip_tags="_{epoch}"): + style="seaborn_v0_8-whitegrid", log_base=10, skip_tags="_{epoch}"): plt.style.use(style) fig, ((ax1, ax2)) = plt.subplots(1, 2, sharex=False, sharey=False, figsize=(18, 6), dpi=200) fig.suptitle('Loss and Dice Coefficient with random ratio set at ' + str(RR) + ' for ' + tf + ' using the ' + ARC + ' architecture', fontsize=22) @@ -259,26 +259,32 @@ def export_prc(precision, recall, file_location, title="Precision Recall Curve", def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_location, prefix, - suffix="_validationPerformance_vs_thresholdCalibration", ext=".png", style="ggplot"): + suffix="_validationPerformance_vs_thresholdCalibration", ext=".png", style="ggplot", + chrom_name="chr2"): """ - Multi-panel plot of Precision, log2(FC), Recall, and F1 vs. Threshold. Each cell type - is drawn in color from its own per-metric curve; the median-across-cell-type curve - is drawn in black on the Precision/Recall/F1 panels. + Multi-panel plot of Precision, Recall, F1 and, when present, Peak_Recall (% of unique + ChIP-seq peaks recovered) vs. Threshold. Each cell type is drawn in color from its own + per-metric curve; the median-across-cell-type curve is drawn in black on every panel. - median_curve: DataFrame with Metric/Precision/Recall/Threshold/log2FC/F1 columns. + median_curve: DataFrame with Metric/Precision/Recall/Threshold/F1 (+ Peak_Recall) columns. cell_type_curves: list of {'name': str, 'curves': {'Precision': DataFrame, - 'Recall': DataFrame, 'F1': DataFrame}}. + 'Recall': DataFrame, 'F1': DataFrame (, 'Peak_Recall': DataFrame)}}. """ plt.style.use(style) + has_peak_recall = (median_curve["Metric"] == "Peak_Recall").any() and \ + all("Peak_Recall" in ct["curves"] for ct in cell_type_curves) fig, axs = plt.subplots(nrows=2, ncols=2, figsize=(15, 12)) # (axis, column, label, median_curve Metric for the black line; None = no black line) panels = [ (axs[0, 0], "Precision", "Precision", "Precision"), - (axs[0, 1], "log2FC", "log2(FC)", None), - (axs[1, 0], "Recall", "Recall", "Recall"), - (axs[1, 1], "F1", "F1 Score", "F1"), + (axs[0, 1], "Recall", "Recall", "Recall"), + (axs[1, 0], "F1", "F1 Score", "F1"), ] + if has_peak_recall: + panels.append((axs[1, 1], "Peak_Recall", "Fraction of Unique Peaks Recovered", "Peak_Recall")) + else: + axs[1, 1].axis("off") n_curves = max(len(cell_type_curves), 1) colors = plt.cm.rainbow(np.linspace(0, 1, n_curves)) @@ -296,9 +302,12 @@ def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_locati ct_curve = ct["curves"][metric_key] ax.plot(ct_curve["Threshold"], ct_curve[col], c=color, lw=1.2, alpha=0.85, label=ct["name"]) if metric_filter is not None: - panel_median = median_curve[median_curve["Metric"] == metric_filter].sort_values("Threshold") + # Bins past some cell types' range can share a median Threshold; break ties on Bin in + # the metric's own direction (Precision rises, Recall/Peak_Recall fall with threshold) + panel_median = median_curve[median_curve["Metric"] == metric_filter].sort_values( + ["Threshold", "Bin"], ascending=[True, metric_filter == "Precision"], kind="mergesort") ax.plot(panel_median["Threshold"], panel_median[col], c="black", lw=3, label="Median") - ax.set_title(f"chr2 Validation {label} v. Thresholds", size="medium") + ax.set_title(f"{chrom_name} Validation {label} v. Thresholds", size="medium") ax.set_xlabel("Threshold", size="medium") ax.set_xlim([0.0, max_threshold]) ax.set_ylabel(f"Validation {label}", size="medium") @@ -307,7 +316,7 @@ def plot_threshold_calibration_stats(median_curve, cell_type_curves, file_locati handles, labels = axs[0, 0].get_legend_handles_labels() fig.legend(handles, labels, loc="lower center", ncol=min(len(labels), 6), fontsize=9, bbox_to_anchor=(0.5, -0.02)) - fig.suptitle(prefix + " chr2 Validation Performance v. Threshold Calibration") + fig.suptitle(f"{prefix} {chrom_name} Validation Performance v. Threshold Calibration") fig.savefig(replace_extension(file_location, prefix + '_' + suffix + ext), bbox_inches="tight", dpi=320) diff --git a/maxatac/utilities/prediction_tools.py b/maxatac/utilities/prediction_tools.py index af355ad..8e6f87f 100644 --- a/maxatac/utilities/prediction_tools.py +++ b/maxatac/utilities/prediction_tools.py @@ -1,11 +1,10 @@ import logging - import numpy as np import pandas as pd import pybedtools import tensorflow as tf -from maxatac.utilities.constants import INPUT_CHANNELS, INPUT_LENGTH, ALL_CHRS +from maxatac.utilities.constants import INPUT_CHANNELS, INPUT_LENGTH, ALL_CHRS, DEFAULT_MAX_ZOOMS from maxatac.utilities.system_tools import Mute with Mute(): @@ -31,6 +30,7 @@ def write_predictions_to_bigwig(df: pd.DataFrame, output_filename: str, chrom_sizes_dictionary: dict, chromosomes: list, + max_zooms: int = DEFAULT_MAX_ZOOMS, agg_mean: bool = True ): """Write the predictions dataframe into a bigwig file @@ -40,10 +40,11 @@ def write_predictions_to_bigwig(df: pd.DataFrame, output_filename (str): The output bigwig filename chrom_sizes_dictionary (dict): A dictionary of chromosome sizes used to form the bigwig file chromosomes (list): A list of chromosomes that you are predicting in - agg_mean (bool, optional): use aggregation method of mean. Defaults to True. + max_zooms (int, optional): The desired number of zoom levels to be retained in the output bigWig file. Defaults to DEFAULT_MAX_ZOOMS (10). + agg_mean (bool, optional): Use aggregation method of mean. Defaults to True. Returns: - Writes a bigwig file + Writes a bigWig file Example: @@ -63,7 +64,7 @@ def write_predictions_to_bigwig(df: pd.DataFrame, header = [(x, chrom_sizes_dictionary[x]) for x in chromosomes] # Add header to bigwig - data_stream.addHeader(header) + data_stream.addHeader(header, maxZooms = max_zooms) for chromosome in chromosomes: # Create a tmp df from the predictions dataframe for each chrom @@ -76,10 +77,9 @@ def write_predictions_to_bigwig(df: pd.DataFrame, data_stream.addEntries(chroms=tmp_chrom_df["chr"].tolist(), starts=tmp_chrom_df["start"].tolist(), ends=tmp_chrom_df["stop"].tolist(), - values=tmp_chrom_df["score"].tolist() + values=tmp_chrom_df["score"].astype(np.float16).tolist() ) - def import_prediction_regions(bed_file: str, chromosomes: list, chrom_sizes_dictionary: dict, @@ -220,7 +220,6 @@ def create_prediction_regions(chromosomes: list, return df - class PredictionDataGenerator(tf.keras.utils.Sequence): def __init__(self, signal, @@ -335,7 +334,6 @@ def __get_region_values__(self, roi_pool): return np.array(inputs_batch) - def make_stranded_predictions(roi_pool: pd.DataFrame, signal: str, sequence: str, diff --git a/maxatac/utilities/save_predictions_callback.py b/maxatac/utilities/save_predictions_callback.py deleted file mode 100644 index da0f98c..0000000 --- a/maxatac/utilities/save_predictions_callback.py +++ /dev/null @@ -1,43 +0,0 @@ -import numpy as np -import os -from tensorflow.keras.callbacks import Callback - -class SavePredictionsCallback(Callback): - def __init__(self, save_dir, prefix="train", save_format="npz"): - super().__init__() - self.save_dir = save_dir - self.prefix = prefix - self.save_format = save_format - os.makedirs(self.save_dir, exist_ok=True) - self.reset_storage() - - def reset_storage(self): - self.all_y_true = [] - self.all_y_pred = [] - - def on_epoch_begin(self, epoch, logs=None): - self.reset_storage() - self.epoch = epoch - - def on_train_batch_end(self, batch, logs=None): - # Ensure model has access to y_true/y_pred - x, y_true = self.model._last_train_batch - y_pred = self.model(x, training=False) - self.all_y_true.append(y_true.numpy()) - self.all_y_pred.append(y_pred.numpy()) - - def on_epoch_end(self, epoch, logs=None): - y_true_all = np.concatenate(self.all_y_true, axis=0) - y_pred_all = np.concatenate(self.all_y_pred, axis=0) - - filename = f"{self.prefix}_epoch{self.epoch:02d}.{self.save_format}" - save_path = os.path.join(self.save_dir, filename) - - if self.save_format == "npz": - np.savez(save_path, y_true=y_true_all, y_pred=y_pred_all) - elif self.save_format == "csv": - np.savetxt(save_path.replace(".csv", "_true.csv"), y_true_all, delimiter=",") - np.savetxt(save_path.replace(".csv", "_pred.csv"), y_pred_all, delimiter=",") - else: - raise ValueError("Unsupported save_format: use 'npz' or 'csv'") - diff --git a/maxatac/utilities/system_tools.py b/maxatac/utilities/system_tools.py index 642160b..6dea4af 100644 --- a/maxatac/utilities/system_tools.py +++ b/maxatac/utilities/system_tools.py @@ -1,10 +1,10 @@ import logging -import pkg_resources +from importlib import metadata import os import sys import subprocess from os import path, getcwd, makedirs, error, walk, environ -from maxatac.utilities.constants import CPP_LOG_LEVEL +from maxatac.utilities.constants import CPP_LOG_LEVEL, maxatac_data_path from re import match from multiprocessing import cpu_count @@ -58,8 +58,12 @@ def get_rootname(l): def get_version(): - pkg = pkg_resources.require("maxatac") - return pkg[0].version if pkg else "unknown version" + # importlib.metadata: pkg_resources was removed from recent setuptools releases + try: + return metadata.version("maxatac") + + except metadata.PackageNotFoundError: + return "unknown version" def remove_tags(l, tags): @@ -207,9 +211,6 @@ def update_reference_genome_paths(args): """ logging.info(f"Generating Paths for genome build: {args.genome} \n") - # build maxatac data path - maxatac_data_path = os.path.join(os.path.expanduser('~'), "opt", "maxatac", "data") - # build genome specific paths blacklist_path = os.path.join(maxatac_data_path, f"{args.genome}/{args.genome}_maxatac_blacklist.bed") # maxATAC extended blacklist as bed diff --git a/maxatac/utilities/threshold_tools.py b/maxatac/utilities/threshold_tools.py index d37baed..86331df 100644 --- a/maxatac/utilities/threshold_tools.py +++ b/maxatac/utilities/threshold_tools.py @@ -5,6 +5,121 @@ from sklearn.metrics import precision_recall_curve +def f1_from_precision_recall(precision, recall): + """ + F1 = 2PR / (P + R), defined as 0 where P = R = 0 (e.g. a cell type with no reachable bins) + instead of NaN, so a single degenerate row cannot propagate through the binning, the + cross-cell-type medians, or the max-F1 lookups. + """ + precision = np.asarray(precision, dtype=float) + recall = np.asarray(recall, dtype=float) + denominator = precision + recall + + return np.divide(2 * precision * recall, denominator, + out=np.zeros_like(denominator), where=denominator > 0) + + +PEAK_RECALL = 'Peak_Recall' + + +def curve_value_columns(df): + """ + Value columns carried through binning/medians: always Precision/Recall/Threshold/F1, + plus Peak_Recall when the curve was built with per-peak predictions. + """ + columns = ['Precision', 'Recall', 'Threshold', 'F1'] + if PEAK_RECALL in df.columns: + columns.append(PEAK_RECALL) + return columns + + +def _intervals_to_peak_bin_pairs(start_bins, end_bins): + """ + Expand half-open bin intervals [start, end) into flat (peak_idx, bin_idx) pairs. + Pairs rather than a label array, because overlapping peaks can share a bin. + """ + start_bins = np.asarray(start_bins, dtype=np.int64) + lengths = np.asarray(end_bins, dtype=np.int64) - start_bins + + peak_idx = np.repeat(np.arange(len(lengths)), lengths) + offsets = np.arange(lengths.sum()) - np.repeat(np.cumsum(lengths) - lengths, lengths) + bin_idx = np.repeat(start_bins, lengths) + offsets + + return peak_idx, bin_idx + + +def import_peak_bed_bins(peaks_bed, chrom_name, chrom_length, bin_count): + """ + Map the unique (chr, start, end) intervals of a ChIP-seq peak BED on chrom_name onto the + bin grid used by get_bigwig_stats (nBins=bin_count over [0, chrom_length), so each bin is + chrom_length / bin_count bp wide). Peaks falling entirely past the last bin are dropped. + + :return: (peak_idx, bin_idx) pairs, one per bin a peak touches + """ + bed = pd.read_csv(peaks_bed, sep="\t", header=None, usecols=[0, 1, 2], + names=['chr', 'start', 'end'], dtype={'chr': str}, comment='#') + # Coercing drops track/browser header lines + bed['start'] = pd.to_numeric(bed['start'], errors='coerce') + bed['end'] = pd.to_numeric(bed['end'], errors='coerce') + bed = bed.dropna() + bed = bed[bed['chr'] == chrom_name].drop_duplicates(subset=['chr', 'start', 'end']) + + start = bed['start'].to_numpy(dtype=np.int64) + end = bed['end'].to_numpy(dtype=np.int64) + + start_bins = start * bin_count // chrom_length + end_bins = np.minimum(-(-end * bin_count // chrom_length), bin_count) + + keep = end_bins > start_bins + return _intervals_to_peak_bin_pairs(start_bins[keep], end_bins[keep]) + + +def gold_standard_run_bins(gold_standard): + """ + Fallback peak definition when no ChIP-seq peak BED is given: each run of consecutive + gold-standard bins is one peak (peaks closer than one bin apart merge). + + :return: (peak_idx, bin_idx) pairs, one per gold-standard bin + """ + gs = np.asarray(gold_standard, dtype=bool).astype(np.int8) + edges = np.diff(np.concatenate(([0], gs, [0]))) + + return _intervals_to_peak_bin_pairs(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)) + + +def peak_max_predictions(predictions, peak_idx, bin_idx, keep_mask=None): + """ + Max prediction per peak over its kept (e.g. non-blacklisted) bins. Peaks with no kept + bin are dropped, so they do not count toward the Peak_Recall denominator. + """ + predictions = np.asarray(predictions, dtype=float) + if keep_mask is not None: + keep = np.asarray(keep_mask, dtype=bool)[bin_idx] + peak_idx, bin_idx = peak_idx[keep], bin_idx[keep] + + if len(peak_idx) == 0: + return np.array([], dtype=float) + + peak_max = np.full(int(peak_idx.max()) + 1, -np.inf) + np.maximum.at(peak_max, peak_idx, predictions[bin_idx]) + + return peak_max[np.isfinite(peak_max)] + + +def peak_recall_at_thresholds(peak_max, thresholds): + """ + Fraction of peaks recovered at each threshold T: a peak counts when any of its bins has + prediction >= T (the same >= rule sklearn uses for bin-level Recall). + """ + thresholds = np.asarray(thresholds, dtype=float) + n_peaks = len(peak_max) + if n_peaks == 0: + return np.zeros_like(thresholds) + + sorted_max = np.sort(peak_max) + return (n_peaks - np.searchsorted(sorted_max, thresholds, side='left')) / n_peaks + + def import_blacklist_mask(bigwig_path, chromosome, chromosome_length, bin_count): """ Import the chromosome signal from a blacklist bigwig file and convert to a numpy array to use to mask out @@ -49,29 +164,40 @@ def calculate_AUC_per_rank(PR_CURVE_DF, threshold): return metrics.auc(y=tmp_df["Precision"], x=tmp_df["Recall"]) -def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins=None): +def compute_calibration_curve(goldstandard, prediction, gs_bins=None, rand_bins=None, peak_max=None): """ - Build a monotonic Precision/Recall/Threshold calibration curve (plus F1) for one - goldstandard/prediction pair. log2FC is added only when gs_bins and rand_bins are given. + Build a Precision/Recall/Threshold calibration curve (plus F1) for one goldstandard/prediction + pair. Every row is a real threshold with the metrics it actually achieves. log2FC is added only + when gs_bins and rand_bins are given; Peak_Recall (fraction of unique ChIP-seq peaks recovered) + only when peak_max, the per-peak max prediction from peak_max_predictions(), is given. + + Only thresholds on the precision-recall frontier are kept: a threshold is dropped when a lower + threshold reaches the same or a higher precision, since that one also has at least the recall + (and Peak_Recall). The kept rows are monotonic in threshold without changing any value. + sklearn's terminal (Precision=1, Recall=0) point has no threshold and is dropped. """ precision, recall, thresholds = precision_recall_curve(goldstandard, prediction) - P = np.maximum.accumulate(np.array(precision)) - R = np.minimum.accumulate(np.array(recall)) + # precision/recall have one more entry than thresholds: the terminal sentinel + precision = np.asarray(precision[:-1]) + recall = np.asarray(recall[:-1]) + + # Thresholds ascend: keep a point only if it beats the precision of every lower threshold + best_below = np.concatenate(([-np.inf], np.maximum.accumulate(precision)[:-1])) + keep = precision > best_below + + curve_df = pd.DataFrame({'Precision': precision[keep], + 'Recall': recall[keep], + 'Threshold': np.asarray(thresholds)[keep]}) - # sklearn returns one fewer threshold than precision/recall; label the terminal - # sentinel row (P=1, R=0) with the last real threshold. - threshold_col = np.append(thresholds, thresholds[-1]) - curve_df = pd.DataFrame({'Precision': P, 'Recall': R, "Threshold": threshold_col}) - # Duplicate the last row rather than forcing Threshold=1 (quant predictions can exceed 1) - new_row = curve_df.tail(n=1) - curve_df = pd.concat([curve_df, new_row], ignore_index=True) + if peak_max is not None: + curve_df[PEAK_RECALL] = peak_recall_at_thresholds(peak_max, curve_df['Threshold']) if gs_bins is not None and rand_bins is not None: random_precision = gs_bins / rand_bins curve_df['log2FC'] = np.log2(curve_df['Precision'] / random_precision) - curve_df['F1'] = 2 * (curve_df['Precision'] * curve_df['Recall']) / (curve_df['Precision'] + curve_df['Recall']) + curve_df['F1'] = f1_from_precision_recall(curve_df['Precision'], curve_df['Recall']) return curve_df @@ -90,7 +216,7 @@ def bin_curve_by_metric(curve_df, metric): binned = binned.rename(columns={'_bin': 'Bin'}) binned['Metric'] = metric - return binned[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']].reset_index(drop=True) + return binned[['Metric', 'Bin'] + curve_value_columns(binned)].reset_index(drop=True) def extend_bins_to_full_grid(binned_df, full_bins=None): @@ -106,17 +232,17 @@ def extend_bins_to_full_grid(binned_df, full_bins=None): binned_df = binned_df.drop_duplicates(subset='Bin').sort_values('Bin').reset_index(drop=True) grid = pd.DataFrame({'Bin': np.sort(np.unique(full_bins))}) + value_columns = curve_value_columns(binned_df) + extended = grid.merge(binned_df, on='Bin', how='left') # Row position equals Bin position on the evenly spaced grid, so linear is exact - extended[['Precision', 'Recall', 'Threshold', 'F1']] = extended[ - ['Precision', 'Recall', 'Threshold', 'F1'] - ].interpolate(method='linear', limit_direction='both') + extended[value_columns] = extended[value_columns].interpolate(method='linear', limit_direction='both') extended['Metric'] = extended['Metric'].ffill().bfill() # Recompute F1 from interpolated P/R for internal consistency - extended['F1'] = 2 * extended['Precision'] * extended['Recall'] / (extended['Precision'] + extended['Recall']) + extended['F1'] = f1_from_precision_recall(extended['Precision'], extended['Recall']) - return extended[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']] + return extended[['Metric', 'Bin'] + value_columns] def median_bins_across_samples(binned_tables, full_bins=None): @@ -129,7 +255,7 @@ def median_bins_across_samples(binned_tables, full_bins=None): extended_tables = [extend_bins_to_full_grid(t, full_bins) for t in binned_tables] merged = pd.concat(extended_tables, ignore_index=True) - combined = merged.groupby('Bin', as_index=False)[['Precision', 'Recall', 'Threshold', 'F1']].median() + combined = merged.groupby('Bin', as_index=False)[curve_value_columns(merged)].median() combined.insert(0, 'Metric', metric) return combined.sort_values('Bin').reset_index(drop=True) @@ -141,7 +267,7 @@ def recompute_f1(median_table): consistent (medians taken per column need not satisfy F1 = 2PR/(P+R)). """ out = median_table.copy() - out['F1'] = 2 * out['Precision'] * out['Recall'] / (out['Precision'] + out['Recall']) + out['F1'] = f1_from_precision_recall(out['Precision'], out['Recall']) return out @@ -158,16 +284,17 @@ def bin_median_table_by_f1(median_tables): binned = pooled.loc[pooled.groupby('Bin')['F1'].idxmax()].copy() binned['Metric'] = 'F1' - return binned[['Metric', 'Bin', 'Precision', 'Recall', 'Threshold', 'F1']].sort_values('Bin').reset_index(drop=True) + return binned[['Metric', 'Bin'] + curve_value_columns(binned)].sort_values('Bin').reset_index(drop=True) def merge_binned_metrics(median_tables): """ - Concatenate the Precision/Recall/F1 tables, ordered by Metric then Bin. No - deduplication across metrics: F1 rows legitimately coincide with Precision/Recall rows. + Concatenate the Precision/Recall/F1 (+ Peak_Recall) tables, ordered by Metric then Bin. + No deduplication across metrics: F1 rows legitimately coincide with Precision/Recall rows. """ merged = pd.concat(median_tables, ignore_index=True) - merged['Metric'] = pd.Categorical(merged['Metric'], categories=['Precision', 'Recall', 'F1'], ordered=True) + merged['Metric'] = pd.Categorical(merged['Metric'], categories=['Precision', 'Recall', 'F1', PEAK_RECALL], + ordered=True) merged = merged.sort_values(['Metric', 'Bin']).reset_index(drop=True) merged['Metric'] = merged['Metric'].astype(str) @@ -178,7 +305,8 @@ def build_cross_cell_type_threshold_table(curves): """ Given one calibration curve per cell type: bin each by Precision and Recall, take the median across cell types per bin, recompute F1, derive the F1 grid from the Recall - table, and merge the three metrics' tables. + table, and merge the metrics' tables. When every curve carries Peak_Recall, it gets its + own grid too (binned and median-aggregated exactly like Recall). """ precision_tables = [bin_curve_by_metric(curve, 'Precision') for curve in curves] recall_tables = [bin_curve_by_metric(curve, 'Recall') for curve in curves] @@ -188,7 +316,12 @@ def build_cross_cell_type_threshold_table(curves): f1_binned = bin_median_table_by_f1([recall_median]) - return merge_binned_metrics([precision_median, recall_median, f1_binned]) + tables = [precision_median, recall_median, f1_binned] + if all(PEAK_RECALL in curve.columns for curve in curves): + peak_recall_tables = [bin_curve_by_metric(curve, PEAK_RECALL) for curve in curves] + tables.append(recompute_f1(median_bins_across_samples(peak_recall_tables))) + + return merge_binned_metrics(tables) def sample_curve_at_thresholds(curve_df, threshold_values): diff --git a/maxatac/utilities/training_tools.py b/maxatac/utilities/training_tools.py index f6b6cb0..b24b6fd 100644 --- a/maxatac/utilities/training_tools.py +++ b/maxatac/utilities/training_tools.py @@ -13,7 +13,7 @@ from maxatac.architectures.dcnn import get_dilated_cnn from maxatac.utilities.constants import BP_RESOLUTION, BATCH_SIZE, CHR_POOL_SIZE, INPUT_LENGTH, INPUT_CHANNELS, \ - BP_ORDER, TRAIN_SCALE_SIGNAL + BP_ORDER, BINARY_TARGET_MIN_PEAK_FRACTION from maxatac.utilities.genome_tools import load_bigwig, load_2bit, get_one_hot_encoded, build_chrom_sizes_dict from maxatac.utilities.system_tools import get_dir, remove_tags, replace_extension @@ -38,7 +38,7 @@ def __init__(self, meta_path, weights, dense=False, - target_scale_factor=TRAIN_SCALE_SIGNAL, + target_scale_factor=1, output_activation="sigmoid", quant=False, interpret=False, @@ -78,8 +78,11 @@ def __init__(self, self.target_scale_factor = target_scale_factor self.loss = loss - # Set the random seed for the model + # Seed every RNG that training draws from: python (ROI sampling), numpy + # (shuffles / random regions) and TensorFlow (weight init, dropout) random.seed(seed) + np.random.seed(seed) + tf.random.set_seed(seed) # Import meta txt as dataframe self.meta_dataframe = pd.read_csv(self.meta_path, sep='\t', header=0, index_col=None) @@ -92,7 +95,7 @@ def __init__(self, self.nn_model = self.__get_model() if interpret: - assert (interpret_cell_type is not None, "Set the interpretation cell type argument") + assert interpret_cell_type is not None, "Set the interpretation cell type argument" self.interpret_cell_type = interpret_cell_type self.__get_interpretation_attributes() @@ -296,6 +299,13 @@ def get_target_matrix(binding_stream, quant, bp_resolution, target_scale_factor): + """ + Build the per-bin training target for one 1,024 bp window from the Binding_File bigwig. + + quant=True: mean signal per bp_resolution bin, times target_scale_factor. + quant=False: 1.0 where more than BINARY_TARGET_MIN_PEAK_FRACTION of the bin's bases are + inside a peak (Binding_File is a 0/1 peak track), else 0.0 (maxATAC v1 rule). + """ # Some bigwig files do not have signal for some chromosomes because they do not have peaks # in those regions # Our workaround for issue#42 is to provide a zero matrix for that position @@ -305,9 +315,9 @@ def get_target_matrix(binding_stream, if target_vector.shape[0] == 0: target_vector = np.zeros(INPUT_LENGTH) - except: - # TODO change length of array - target_vector = np.zeros(1024) + except (RuntimeError, KeyError, ValueError): + # pyBigWig raises RuntimeError when a chromosome is absent from the file + target_vector = np.zeros(INPUT_LENGTH) # change nan to numbers target_vector = np.nan_to_num(target_vector, 0.0) @@ -327,9 +337,9 @@ def get_target_matrix(binding_stream, bin_vector = bin_vector * target_scale_factor else: - # TODO we might want to test what happens if we change the + # Number of peak bases per bin; bound if more than the configured fraction of the bin bin_sums = np.sum(split_targets, axis=1) - bin_vector = np.where(bin_sums > 0.5 * bp_resolution, 1.0, 0.0) + bin_vector = np.where(bin_sums > BINARY_TARGET_MIN_PEAK_FRACTION * bp_resolution, 1.0, 0.0) return bin_vector @@ -906,7 +916,12 @@ def model_selection(training_history, output_dir): def model_selection_v2(training_history, output_dir): """ - This function will take the training history and output the best model based on the dice coefficient value. + Select the best epoch for a quantitative model from the training history. + + Starting at the epoch with the minimum validation loss, pick the epoch (at or after it) + with the smallest normalized train/validation gap |val_loss - loss| / max(val_loss, loss), + so the chosen checkpoint has both low validation loss and little overfitting. + Writes best_epoch.txt with the checkpoint path and returns the 1-based epoch number. """ # Create a dataframe from the history object df = pd.DataFrame(training_history.history) diff --git a/setup.py b/setup.py index b0d80cb..8f4f6ac 100644 --- a/setup.py +++ b/setup.py @@ -1,46 +1,50 @@ #! /usr/bin/env python3 import os -import time import subprocess from setuptools import setup, find_packages GIT_VERSION_FILE = os.path.join("maxatac", "git_version") HERE = os.path.abspath(os.path.dirname(__file__)) +# Version of an untagged commit. A development version makes `maxatac data` install the latest data +DEV_VERSION = "2.0.0.dev0" -def get_git_tag(): - return subprocess.check_output(["git", "describe", "--contains"], text=True).split("^")[0].strip() - -def get_git_timestamp(): - gitinfo = subprocess.check_output( - ["git", "log", "--first-parent", "--max-count=1", "--format=format:%ct", "."], text=True).strip() - return time.strftime("%Y%m%d%H%M%S", time.gmtime(int(gitinfo))) +def git(*args): + return subprocess.check_output(["git", *args], cwd=HERE, text=True, stderr=subprocess.DEVNULL).strip() def get_version(): """ Tries to get package version with following order: - 0. default version - 1. from git_version file - when installing from pip, this is the only source to get version - 2. from tag - 3. from commit timestamp + 1. in a git checkout: the tag on the current commit without its leading "v" (v2.0.0b1 -> 2.0.0b1), + or DEV_VERSION if the commit is not tagged + 2. outside git (installing from an sdist): the git_version file written when the sdist was built + 3. DEV_VERSION + Tags must be PEP 440 versions: `maxatac data` installs the data repository tag of the same name. Updates/creates git_version file with the package version Returns package version """ - version = "1.9.2" # default version - try: - with open(GIT_VERSION_FILE, "r") as input_stream: # try to get version info from file - version = input_stream.read() - except Exception: - pass + version = DEV_VERSION try: - version = get_git_tag() # try to get version info from the closest tag + git("rev-parse", "--git-dir") + in_git = True except Exception: + in_git = False + + if in_git: + try: + tag = git("describe", "--tags", "--exact-match") + version = tag[1:] if tag.startswith("v") else tag + except Exception: + pass + + else: try: - version = "1.9.2" # try to get version info from commit date + with open(GIT_VERSION_FILE, "r") as input_stream: + version = input_stream.read().strip() or DEV_VERSION except Exception: pass @@ -54,7 +58,7 @@ def get_version(): def get_description(): README = os.path.join(HERE, "README.md") - with open(README, "r") as f: + with open(README, "r", encoding="utf-8") as f: return f.read() setup( @@ -79,8 +83,11 @@ def get_description(): "tests" ] ), + python_requires=">=3.9", install_requires=[ - "tensorflow", + # Keras 2 API: tf.keras.utils.OrderedEnqueuer and Adam(weight_decay=) need >=2.11, + # and both were dropped with Keras 3 in TF 2.16 + "tensorflow>=2.14,<2.16", "tensorboard", "biopython", "py2bit", @@ -88,6 +95,7 @@ def get_description(): "pydot", "matplotlib", "scikit-learn", + "scipy", "pybedtools", "pandas", "pyfiglet", @@ -98,6 +106,10 @@ def get_description(): "tqdm", "ushuffle" ], + extras_require={ + # Only the multinomialnll* losses need it + "multinomial": ["tensorflow-probability>=0.22,<0.24"], + }, zip_safe=False, scripts=["maxatac/bin/maxatac"], classifiers=[] diff --git a/tests/e2e/baseline.json b/tests/e2e/baseline.json new file mode 100644 index 0000000..5af24a1 --- /dev/null +++ b/tests/e2e/baseline.json @@ -0,0 +1,13 @@ +{ + "_comment": "Reference metrics for tests/e2e/run_e2e.sh (GM12878 CTCF, chr1:1,000,000-11,000,000). null = not seeded yet: copy the values from the metrics.json artifact of a green run. A run fails when a metric drops below baseline - tolerance.", + "metrics": { + "AUPRC": null, + "pearson": null, + "spearman": null + }, + "tolerance": { + "AUPRC": 0.02, + "pearson": 0.03, + "spearman": 0.03 + } +} diff --git a/tests/e2e/check_outputs.py b/tests/e2e/check_outputs.py new file mode 100644 index 0000000..10c5319 --- /dev/null +++ b/tests/e2e/check_outputs.py @@ -0,0 +1,245 @@ +#!/usr/bin/env python3 +"""Output checks for the end-to-end test (tests/e2e/run_e2e.sh) + +Subcommands: + data the reference files and the TF model installed by `maxatac data` are present + whitelist write a bigWig that is 1 over the ROI, used to restrict `maxatac benchmark` to it + prediction the prediction bigWig and peaks look sane over the ROI + report collect the metrics, compare them with the baseline and write a summary +""" +import argparse +import glob +import json +import os +import sys + +import numpy as np +import pandas as pd +import pyBigWig +from scipy import stats + +BIN_SIZE = 200 + + +def fail(message): + # ::error:: is shown as an annotation on GitHub Actions and is plain text elsewhere + print(f"::error::{message}") + sys.exit(1) + + +def read_roi(roi_path): + """Return (chrom, start, end) of the first interval in a BED file""" + with open(roi_path) as roi: + chrom, start, end = roi.readline().split("\t")[:3] + + return chrom, int(start), int(end) + + +def binned_stats(bigwig_path, chrom, start, end, agg="mean", bin_size=BIN_SIZE): + """Aggregate a bigWig into fixed bins over [start, end); bins without data are NaN""" + n_bins = (end - start) // bin_size + bigwig = pyBigWig.open(bigwig_path) + + try: + values = bigwig.stats(chrom, start, start + n_bins * bin_size, type=agg, nBins=n_bins) + + finally: + bigwig.close() + + return np.array(values, dtype=float) + + +def check_data(args): + genome_dir = os.path.join(args.data_dir, args.genome) + required = [os.path.join(genome_dir, f"{args.genome}.chrom.sizes"), + os.path.join(genome_dir, f"{args.genome}_maxatac_blacklist.bed"), + os.path.join(genome_dir, f"{args.genome}_maxatac_blacklist.bw"), + os.path.join(genome_dir, f"{args.genome}.2bit")] + + for path in required: + if not os.path.isfile(path) or os.path.getsize(path) == 0: + fail(f"`maxatac data` did not install {path}") + + model_dir = os.path.join(args.data_dir, "models", args.tf) + models = glob.glob(os.path.join(model_dir, f"{args.tf}*.h5")) + tables = glob.glob(os.path.join(model_dir, f"{args.tf}*_cross_celltype.tsv")) + + if not models: + fail(f"No {args.tf} model (*.h5) in {model_dir}") + + if not tables: + fail(f"No {args.tf} threshold calibration table (*_cross_celltype.tsv) in {model_dir}") + + print(f"Reference data OK: {genome_dir}") + print(f"Model: {models[0]}") + print(f"Calibration table: {tables[0]}") + + +def write_whitelist(args): + chrom, start, end = read_roi(args.roi) + chrom_sizes = pd.read_csv(args.chrom_sizes, sep="\t", header=None, index_col=0)[1] + + whitelist = pyBigWig.open(args.out, "w") + whitelist.addHeader([(chrom, int(chrom_sizes[chrom]))]) + whitelist.addEntries([chrom], [start], ends=[end], values=[1.0]) + whitelist.close() + + print(f"Wrote {args.out}: {chrom}:{start}-{end}") + + +def check_prediction(args): + if not os.path.isfile(args.prediction): + fail(f"`maxatac predict` did not write {args.prediction}") + + chrom, start, end = read_roi(args.roi) + + prediction = pyBigWig.open(args.prediction) + chroms = prediction.chroms() + prediction.close() + + if chrom not in chroms: + fail(f"{args.prediction} has no {chrom}; chromosomes: {list(chroms)}") + + values = binned_stats(args.prediction, chrom, start, end, agg="max") + covered = np.isfinite(values) + + # Blacklisted windows are not predicted, so full coverage is not expected + if covered.mean() < 0.5: + fail(f"Only {covered.mean():.1%} of the {BIN_SIZE} bp bins in the ROI have a prediction") + + covered_values = values[covered] + + if covered_values.min() < 0: + fail(f"Negative prediction scores (min {covered_values.min():.4g}); the quant models end in softplus") + + if np.std(covered_values) == 0: + fail(f"The prediction is constant ({covered_values[0]:.4g}) over the ROI") + + if not os.path.isfile(args.peaks) or os.path.getsize(args.peaks) == 0: + fail(f"`maxatac predict` called no peaks: {args.peaks} is missing or empty") + + peaks = pd.read_csv(args.peaks, sep="\t", header=None, usecols=[0, 1, 2]) + + print(f"Prediction OK: {covered.mean():.1%} of bins covered, " + f"score range {covered_values.min():.4g}-{covered_values.max():.4g}, {len(peaks)} peaks") + + +def report(args): + chrom, start, end = read_roi(args.roi) + + prc = pd.read_csv(args.prc, sep="\t") + metrics = {"AUPRC": float(prc["AUPRC"].iloc[0])} + + if "Random_AUPRC" in prc.columns: + metrics["Random_AUPRC"] = float(prc["Random_AUPRC"].iloc[0]) + + # Interim quantitative check until a null track for `maxatac benchmark --quant` is in the test data + prediction = binned_stats(args.prediction, chrom, start, end, agg="mean") + observed = binned_stats(args.quant_gold_standard, chrom, start, end, agg="mean") + blacklisted = binned_stats(args.blacklist_bw, chrom, start, end, agg="max") > 0 + + # Bins without gold standard signal are 0, not missing + observed = np.nan_to_num(observed, nan=0.0) + keep = np.isfinite(prediction) & ~blacklisted + + metrics["pearson"] = float(stats.pearsonr(prediction[keep], observed[keep])[0]) + metrics["spearman"] = float(stats.spearmanr(prediction[keep], observed[keep])[0]) + metrics["n_bins"] = int(keep.sum()) + + failures = [] + + if "Random_AUPRC" in metrics and metrics["AUPRC"] <= metrics["Random_AUPRC"]: + failures.append(f"AUPRC {metrics['AUPRC']:.4f} is not above random ({metrics['Random_AUPRC']:.4f})") + + if metrics["pearson"] <= 0: + failures.append(f"Pearson correlation with the quantitative gold standard is {metrics['pearson']:.4f}") + + with open(args.baseline) as baseline_file: + baseline = json.load(baseline_file) + + rows = [] + + for name, reference in baseline["metrics"].items(): + tolerance = baseline["tolerance"][name] + value = metrics[name] + + if reference is None: + status = "no baseline" + + elif value < reference - tolerance: + status = "REGRESSED" + failures.append(f"{name} {value:.4f} is below the baseline {reference:.4f} - {tolerance}") + + else: + status = "ok" + + rows.append(f"| {name} | {value:.4f} | {'-' if reference is None else f'{reference:.4f}'} | {status} |") + + with open(args.metrics_out, "w") as metrics_file: + json.dump(metrics, metrics_file, indent=2) + + summary = "\n".join([f"### quant-maxATAC e2e: GM12878 {chrom}:{start:,}-{end:,}", + "", + "| Metric | Value | Baseline | Status |", + "|---|---|---|---|", + *rows, + "", + f"Random AUPRC: {metrics.get('Random_AUPRC', float('nan')):.4f}; " + f"{metrics['n_bins']} {BIN_SIZE} bp bins outside the blacklist", + ""]) + + print(summary) + + # Also kept as a file: release.yml puts it in the GitHub Release notes + with open(os.path.splitext(args.metrics_out)[0] + ".md", "w") as summary_file: + summary_file.write(summary) + + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as step_summary: + step_summary.write(summary + "\n") + + for failure in failures: + print(f"::error::{failure}") + + if failures: + sys.exit(1) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + subparsers = parser.add_subparsers(dest="command", required=True) + + data = subparsers.add_parser("data") + data.add_argument("--data_dir", required=True) + data.add_argument("--genome", required=True) + data.add_argument("--tf", required=True) + data.set_defaults(func=check_data) + + whitelist = subparsers.add_parser("whitelist") + whitelist.add_argument("--roi", required=True) + whitelist.add_argument("--chrom_sizes", required=True) + whitelist.add_argument("--out", required=True) + whitelist.set_defaults(func=write_whitelist) + + prediction = subparsers.add_parser("prediction") + prediction.add_argument("--prediction", required=True) + prediction.add_argument("--peaks", required=True) + prediction.add_argument("--roi", required=True) + prediction.set_defaults(func=check_prediction) + + metrics = subparsers.add_parser("report") + metrics.add_argument("--prc", required=True) + metrics.add_argument("--prediction", required=True) + metrics.add_argument("--quant_gold_standard", required=True) + metrics.add_argument("--blacklist_bw", required=True) + metrics.add_argument("--roi", required=True) + metrics.add_argument("--baseline", required=True) + metrics.add_argument("--metrics_out", required=True) + metrics.set_defaults(func=report) + + args = parser.parse_args() + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tests/e2e/run_e2e.sh b/tests/e2e/run_e2e.sh new file mode 100644 index 0000000..923d83e --- /dev/null +++ b/tests/e2e/run_e2e.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +# End-to-end test of the user path: maxatac data -> maxatac predict -> maxatac benchmark +# +# Predicts one TF on a slice of chr1 from the GM12878 test inputs in +# https://github.com/XiaotingChen/quant-maxATAC_test_data (Git LFS: clone with `git lfs` installed) +# and benchmarks the prediction against the ChIP-seq gold standard on the same slice. +# +# Used by .github/workflows/e2e.yml; runs the same way on a workstation or the cluster: +# TEST_DATA=/path/to/quant-maxATAC_test_data/data bash tests/e2e/run_e2e.sh +# +# Environment (all optional): +# TEST_DATA directory with the test inputs Default: test_data/data +# OUT output directory Default: e2e_out +# TF TF to predict (model from `maxatac data`) Default: CTCF +# ROI_START start of the chr1 slice Default: 1000000 +# ROI_END end of the chr1 slice Default: 11000000 +# DATA_VERSION data repository tag/branch for `maxatac data --data_version` Default: matches the code version +# SKIP_DATA 1 = reuse the installed data, skip `maxatac data` +set -euo pipefail + +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +TEST_DATA="${TEST_DATA:-test_data/data}" +OUT="${OUT:-e2e_out}" +TF="${TF:-CTCF}" +CHROM=chr1 +ROI_START="${ROI_START:-1000000}" +ROI_END="${ROI_END:-11000000}" +GENOME=hg38 +DATA_DIR="${HOME}/opt/maxatac/data" +PREFIX="GM12878_${TF}_e2e" + +ATAC_SIGNAL="${TEST_DATA}/GM12878_RP20M_minmax_percentile99_chr1.bw" +GOLD_STANDARD="${TEST_DATA}/GM12878__${TF}.bw" +QUANT_GOLD_STANDARD="${TEST_DATA}/GM12878__${TF}_quantLinearFC_chr1.bw" + +CHECK="python ${HERE}/check_outputs.py" + +mkdir -p "${OUT}" + +for input in "${ATAC_SIGNAL}" "${GOLD_STANDARD}" "${QUANT_GOLD_STANDARD}"; do + # An LFS pointer is ~130 bytes: catch a clone made without git-lfs early + if [ ! -s "${input}" ] || [ "$(wc -c < "${input}")" -lt 1024 ]; then + echo "::error::Missing test input or unresolved Git LFS pointer: ${input}" + exit 1 + fi +done + +echo "::group::maxatac data" +if [ "${SKIP_DATA:-0}" != "1" ]; then + maxatac data --genome "${GENOME}" --yes ${DATA_VERSION:+--data_version "${DATA_VERSION}"} +fi +${CHECK} data --data_dir "${DATA_DIR}" --genome "${GENOME}" --tf "${TF}" +echo "::endgroup::" + +echo "::group::Region of interest" +# Prediction is limited to one slice of chr1 so it runs on a CPU runner in minutes +printf "%s\t%s\t%s\n" "${CHROM}" "${ROI_START}" "${ROI_END}" > "${OUT}/roi.bed" +# chr1-only chrom sizes, so the sliding windows are not built genome wide +awk -v c="${CHROM}" '$1 == c' "${DATA_DIR}/${GENOME}/${GENOME}.chrom.sizes" > "${OUT}/${CHROM}.chrom.sizes" +# benchmark has no region option: restrict it to the ROI with a whitelist bigWig +${CHECK} whitelist --roi "${OUT}/roi.bed" --chrom_sizes "${OUT}/${CHROM}.chrom.sizes" --out "${OUT}/roi_whitelist.bw" +cat "${OUT}/roi.bed" +echo "::endgroup::" + +echo "::group::maxatac predict" +maxatac predict \ + --tf_name "${TF}" \ + --signal "${ATAC_SIGNAL}" \ + --chromosomes "${CHROM}" \ + --chrom_sizes "${OUT}/${CHROM}.chrom.sizes" \ + --roi "${OUT}/roi.bed" \ + --threads 1 \ + --batch_size 2000 \ + --prefix "${PREFIX}" \ + --output "${OUT}/predict" +${CHECK} prediction --prediction "${OUT}/predict/${PREFIX}.bw" --peaks "${OUT}/predict/${PREFIX}_peaks.bed" \ + --roi "${OUT}/roi.bed" +echo "::endgroup::" + +echo "::group::maxatac benchmark" +maxatac benchmark \ + --bw "${OUT}/predict/${PREFIX}.bw" \ + --gold_standard "${GOLD_STANDARD}" \ + --whitelist_bw "${OUT}/roi_whitelist.bw" \ + --chromosomes "${CHROM}" \ + --bin_size 200 \ + --agg max \ + --plot \ + --prefix "${PREFIX}" \ + --output_directory "${OUT}/benchmark" +echo "::endgroup::" + +echo "::group::Metrics" +${CHECK} report \ + --prc "${OUT}/benchmark/${PREFIX}_${CHROM}_200bp_PRC.tsv" \ + --prediction "${OUT}/predict/${PREFIX}.bw" \ + --quant_gold_standard "${QUANT_GOLD_STANDARD}" \ + --blacklist_bw "${DATA_DIR}/${GENOME}/${GENOME}_maxatac_blacklist.bw" \ + --roi "${OUT}/roi.bed" \ + --baseline "${HERE}/baseline.json" \ + --metrics_out "${OUT}/metrics.json" +echo "::endgroup::" diff --git a/tests/run_tests.sh b/tests/run_tests.sh deleted file mode 100755 index 3565614..0000000 --- a/tests/run_tests.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/bash - -DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )" - -#pip3 install -r $DIR/../test_requirements.txt -pip3 install -r $DIR/test_requirements.txt --use-feature=2020-resolver - -cd $DIR -mkdir -p temp -cd temp - -if [ ! -f "hg19.2bit" ] ; then - echo "Downloading hg19.2bit" - wget -q http://hgdownload.cse.ucsc.edu/goldenPath/hg19/bigZips/hg19.2bit -O hg19.2bit -fi - -if [ ! -f "predict_signal_cell_GM12878.bigwig" ] ; then - echo "Downloading predict_signal_cell_GM12878.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/GM12878.bigwig -O predict_signal_cell_GM12878.bigwig -fi - -if [ ! -f "train_signal_cell_A549.bigwig" ] ; then - echo "Downloading train_signal_cell_A549.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/A549.bigwig -O train_signal_cell_A549.bigwig -fi - -if [ ! -f "validate_signal_cell_HCT116.bigwig" ] ; then - echo "Downloading validate_signal_cell_HCT116.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/HCT116.bigwig -O validate_signal_cell_HCT116.bigwig -fi - -if [ ! -f "average.bigwig" ] ; then - echo "Downloading average.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/dnase_bigwig/avg.bigwig -O average.bigwig -fi - -if [ ! -f "train_sites_cell_A549_tf_CTCF.bigwig" ] ; then - echo "Downloading train_sites_cell_A549_tf_CTCF.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/chipseq_conservative_refine_bigwig/CTCF_A549.bigwig -O train_sites_cell_A549_tf_CTCF.bigwig -fi - -if [ ! -f "validate_sites_cell_HCT116_tf_CTCF.bigwig" ] ; then - echo "Downloading validate_sites_cell_HCT116_tf_CTCF.bigwig" - wget -q https://guanfiles.dcmb.med.umich.edu/test_chipseq_conservative_refine_bigwig/CTCF_HCT116.bigwig -O validate_sites_cell_HCT116_tf_CTCF.bigwig -fi - -if [ ! -f "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" ] ; then - echo "Downloading GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - wget -q https://ftp.ncbi.nlm.nih.gov/geo/series/GSE143nnn/GSE143104/suppl/GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed -fi - -cd .. - -pytest -v --cov=maxatac --forked . diff --git a/tests/test.sh b/tests/test.sh deleted file mode 100644 index 4c9703b..0000000 --- a/tests/test.sh +++ /dev/null @@ -1,52 +0,0 @@ -#!/bin/bash - -module load bedtools/2.30.0 -module load anaconda3 -source activate maxATAC_IS59 - - -mkdir -p /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1 -cd /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1 - -maxatac train \ ---rand_ratio .30 \ ---arch DCNN_V2 \ ---atac_delta \ ---loss_name clipped_cross_entropy \ ---output_activation 'softmax' \ ---sequence /data/miraldiLab/databank/maxatac/maxATAC_inputs/genome_inf/hg38.2bit \ ---meta_file /scratch/war9qi/ARNT_revcomp_99percentile_Binary_Train.tsv \ ---output /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/training_results \ ---prefix ARNT_binary_archs \ ---batch_size 1000 \ ---val_batch_size 1000 \ ---batches 100 \ ---epochs 30 \ ---threads 8 \ ---shuffle_cell_type - - -declare -a best_model_path=$(cat /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/training_results/*txt) -for best_model in ${best_model_path[@]}; do - maxatac predict \ - --models ${best_model} \ - --sequence /data/miraldiLab/databank/maxatac/maxATAC_inputs/genome_inf/hg38.2bit \ - --signal /data/miraldiLab/databank/maxatac/maxATAC_inputs/ATAC/hg38/normalization/GM12878__minmax_percentile99.bw \ - --chromosomes chr1 \ - --prefix ARNT_binary_revcomp99_RR30 \ - --output /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/prediction_results \ - --step_size 256 -done - -declare -a bp_RES=(200) - -for item in ${bp_RES[@]}; do - maxatac benchmark \ - --prediction /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/prediction_results/ARNT_binary_revcomp99_RR30.bw \ - --gold_standard /data/miraldiLab/databank/maxatac/maxatac_goldstandards/hg38/binary/GM12878__ARNT.bw \ - --prefix ARNT_binary_revcomp99_RR30_benchmark \ - --bin_size ${item} \ - --agg max \ - --chromosomes chr1 \ - --output /scratch/war9qi/data/aronow/Balaji_Iyer/Projects/Maxatac_IS59/Maxatac_Predictions/20211015_DCNN_ATAC_DELTA/ARNT1/benchmarking_results -done diff --git a/tests/test_average.py b/tests/test_average.py new file mode 100644 index 0000000..105fcb5 --- /dev/null +++ b/tests/test_average.py @@ -0,0 +1,22 @@ +import os + +import pytest + + +def test_average_defaults_chrom_sizes_to_the_genome_bundle(): + # parse_arguments also runs update_reference_genome_paths, which fills args.chrom_sizes from --genome + parser_module = pytest.importorskip("maxatac.utilities.parser") + from maxatac.utilities.constants import maxatac_data_path + + args = parser_module.parse_arguments(["average", "-i", "a.bw", "b.bw", "-n", "average_test"]) + + assert args.chrom_sizes == os.path.join(maxatac_data_path, "hg38/hg38.chrom.sizes") + + +def test_average_keeps_an_explicit_chrom_sizes_file(): + parser_module = pytest.importorskip("maxatac.utilities.parser") + + args = parser_module.parse_arguments(["average", "-i", "a.bw", "-n", "average_test", + "--chromosome_sizes", "custom.chrom.sizes"]) + + assert args.chrom_sizes == "custom.chrom.sizes" diff --git a/tests/test_average/test_average.py b/tests/test_average/test_average.py deleted file mode 100644 index 3c94626..0000000 --- a/tests/test_average/test_average.py +++ /dev/null @@ -1,85 +0,0 @@ -import os -import pytest -from maxatac.analyses.average import run_averaging -from maxatac.utilities.system_tools import Namespace -from maxatac.utilities.constants import ALL_CHRS -import subprocess - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -input_file_paths = ["../data/average/SRX10474876_Tn5_slop20_blacklisted.bw", - "../data/average/SRX10474877_Tn5_slop20_blacklisted.bw"] - -expected_outputs = {"../data/average/IMR-90_single_chrom.bw": "6194b2bc8ddd1f8b9e277e21a79d9297", - "../data/average/IMR-90_multi_chrom.bw": "46775111a72df9fc54c8c9d153135272", - "../data/average/IMR-90_all_chrom.bw": "a7b2b7b1be22a046d49cff36ba46e8ea"} - -chrom_sizes_path = "~/opt/maxatac/data/hg38/hg38.chrom.sizes" - -def test_average_multi_chrom(): - """ - Test that maxatac average can produce a .bw that has been filtered for chr22 and chr3 - - """ - args_test_multi_chrom = Namespace(bigwig_files=input_file_paths, - output_dir=DATA_FOLDER, - name="average_multi_chrom_test", - chromosomes=["chr22", "chr3"], - chromosome_sizes=chrom_sizes_path - ) - - run_averaging(args_test_multi_chrom) - - output_file = os.path.join(DATA_FOLDER, "average_multi_chrom_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/average/IMR-90_multi_chrom.bw"] - - -def test_average_single_chrom(): - """ - Test that maxatac average can produce a .bw file that has only a single chromosome - - """ - args_test_single_chrom = Namespace(bigwig_files=input_file_paths, - output_dir=DATA_FOLDER, - name="average_single_chrom_test", - chromosomes=["chr22"], - chromosome_sizes=chrom_sizes_path - ) - - run_averaging(args_test_single_chrom) - - output_file = os.path.join(DATA_FOLDER, "average_single_chrom_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/average/IMR-90_single_chrom.bw"] - - -def test_average_all_chrom(): - """ - Test that maxatac average can produce a .bw file that uses all chromosome - - """ - args_test_all_chrom = Namespace(bigwig_files=input_file_paths, - output_dir=DATA_FOLDER, - name="average_all_chrom_test", - chromosomes=ALL_CHRS, - chromosome_sizes=chrom_sizes_path - ) - - run_averaging(args_test_all_chrom) - - output_file = os.path.join(DATA_FOLDER, "average_all_chrom_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/average/IMR-90_all_chrom.bw"] diff --git a/tests/test_benchmark.py b/tests/test_benchmark.py index 10f421f..87b8001 100644 --- a/tests/test_benchmark.py +++ b/tests/test_benchmark.py @@ -40,3 +40,363 @@ def test_parse_benchmark_with_alternative_prediction_arguments(): assert args.alternative_prediction.endswith("predict_signal_cell_GM12878.bigwig") assert args.prediction_combine_operation == "max" + + +def test_precision_for_recall_interpolates_between_bracketing_points(): + import pandas as pd + from maxatac.utilities.benchmarking_tools import Precision_for_Recall + + # PR curve given in sklearn order (recall descending), including the (R=0, P=1) sentinel + curve = pd.DataFrame({ + "Recall": [0.30, 0.20, 0.05, 0.0], + "Precision": [0.40, 0.60, 0.90, 1.0], + }) + + # 0.1 lies between (0.05, 0.90) and (0.20, 0.60): 0.90 + (0.60 - 0.90) * (0.05 / 0.15) + assert Precision_for_Recall(curve, 0.10) == pytest.approx(0.80) + # Exact hits return the point itself + assert Precision_for_Recall(curve, 0.20) == pytest.approx(0.60) + # Beyond the curve's max recall, hold the endpoint + assert Precision_for_Recall(curve, 0.50) == pytest.approx(0.40) + + +def test_precision_for_recall_collapses_duplicate_recall_to_max_precision(): + import pandas as pd + from maxatac.utilities.benchmarking_tools import Precision_for_Recall + + curve = pd.DataFrame({ + "Recall": [0.2, 0.1, 0.1, 0.0], + "Precision": [0.5, 0.7, 0.9, 1.0], + }) + + assert Precision_for_Recall(curve, 0.10) == pytest.approx(0.9) + assert Precision_for_Recall(curve, 0.15) == pytest.approx(0.7) + + +class _StubGoldStandard: + """pyBigWig stand-in returning fixed per-bin stats""" + + def __init__(self, bins): + self.bins = bins + + def stats(self, chromosome, start, end, type, nBins, exact): + return list(self.bins) + + +def test_random_auprc_counts_gold_standard_bins_inside_the_evaluated_mask(tmp_path): + import pandas as pd + from maxatac.utilities.benchmarking_tools import ChromosomeAUPRC + + # 200 bins, the first 100 bound. The mask (blacklist and whitelist combined) keeps 10 bins, 2 of them bound + gold_standard = np.zeros(200) + gold_standard[:100] = 1 + mask = np.zeros(200, dtype=bool) + mask[98:108] = True + + # Bypass __init__ (bigwig I/O) and run the gold standard import and AUPRC steps on in-memory arrays + auprc = ChromosomeAUPRC.__new__(ChromosomeAUPRC) + auprc.chromosome = "chr1" + auprc.chromosome_length = 200 * 200 + auprc.bin_count = 200 + auprc.bin_size = 200 + auprc.agg_function = "max" + auprc.agg_threshold = 0.5 + auprc.peak_based = False + auprc.blacklist_mask = mask + auprc.goldstandard_stream = _StubGoldStandard(gold_standard) + auprc.prediction_array = np.linspace(1, 0, 200) + auprc.results_location = str(tmp_path / "chr1_PRC.tsv") + + auprc.__import_goldstandard_array__() + auprc.__AUPRC__() + + results = pd.read_csv(auprc.results_location, sep="\t") + + # Before the fix: 100 chromosome-wide positives / 10 evaluated bins = 10 + assert results["Total_GoldStandard_Bins"].iloc[0] == 2 + assert results["Random_AUPRC"].iloc[0] == pytest.approx(0.2) + assert results["Random_AUPRC"].iloc[0] == pytest.approx(auprc.random_precision) + + +def _peak_gold_standard(peak_sizes, gap, rng): + """Boolean bins: peaks of the given sizes separated by random negative gaps of at least 1 bin""" + bins = [] + for size in peak_sizes: + bins += [False] * int(rng.integers(1, gap + 1)) + [True] * size + return np.array(bins + [False] * gap) + + +def test_random_aup_ucper_matches_mean_of_random_rankings(): + from maxatac.utilities.benchmarking_tools import (peak_gs_array_to_member_array, + precision_recall_curve_peak_based, + random_aup_ucper) + from sklearn import metrics + + # The analytic curve is the expected curve, so it is about 1/peaks below the mean of shuffled + # rankings (8% at 20 peaks). Use 500 peaks so that bias is well under the tolerance + rng = np.random.default_rng(0) + member = peak_gs_array_to_member_array(_peak_gold_standard([1, 2, 3, 5, 8] * 100, 30, rng)) + + simulated = [] + for _ in range(100): + precision, recall, _ = precision_recall_curve_peak_based(member, rng.random(len(member))) + simulated.append(metrics.auc(x=recall[:-1], y=precision[:-1])) + + assert random_aup_ucper(member) == pytest.approx(np.mean(simulated), rel=0.05) + + +def test_random_aup_ucper_is_flat_bin_level_baseline_for_single_bin_peaks(): + from maxatac.utilities.benchmarking_tools import peak_gs_array_to_member_array, random_aup_ucper + + gold_standard = _peak_gold_standard([1] * 25, 10, np.random.default_rng(1)) + member = peak_gs_array_to_member_array(gold_standard) + + # Flat at P/N; the curve starts at recall 1/N rather than 0, hence the small tolerance + assert random_aup_ucper(member) == pytest.approx(gold_standard.mean(), rel=0.01) + + +def test_random_aup_ucper_lies_between_end_and_start_precision(): + from maxatac.utilities.benchmarking_tools import peak_gs_array_to_member_array, random_aup_ucper + + gold_standard = _peak_gold_standard([4, 10, 20, 6] * 5, 40, np.random.default_rng(2)) + member = peak_gs_array_to_member_array(gold_standard) + n_peaks = len(np.unique(member[member > 0])) + n_negative = np.count_nonzero(member < 0) + + assert n_peaks / (n_peaks + n_negative) < random_aup_ucper(member) < gold_standard.mean() + + +def test_random_precision_at_ucper_matches_mean_of_random_rankings(): + from maxatac.utilities.benchmarking_tools import (Precision_for_Recall, + peak_gs_array_to_member_array, + precision_recall_curve_peak_based, + random_precision_at_ucper) + import pandas as pd + + rng = np.random.default_rng(3) + member = peak_gs_array_to_member_array(_peak_gold_standard([1, 2, 3, 5, 8] * 100, 30, rng)) + + simulated = [] + for _ in range(100): + precision, recall, _ = precision_recall_curve_peak_based(member, rng.random(len(member))) + curve = pd.DataFrame({"Precision": precision[:-1], "Recall": recall[:-1]}) + simulated.append(Precision_for_Recall(curve, 0.1)) + + assert random_precision_at_ucper(member, 0.1) == pytest.approx(np.mean(simulated), rel=0.03) + + +def test_peak_based_auprc_writes_random_baselines(tmp_path): + import pandas as pd + from maxatac.utilities.benchmarking_tools import (ChromosomeAUPRC, peak_gs_array_to_member_array, + random_aup_ucper, random_precision_at_ucper) + + gold_standard = _peak_gold_standard([1, 2, 3, 5, 8] * 20, 30, np.random.default_rng(4)).astype(float) + n_bins = len(gold_standard) + + auprc = ChromosomeAUPRC.__new__(ChromosomeAUPRC) + auprc.chromosome = "chr1" + auprc.chromosome_length = n_bins * 200 + auprc.bin_count = n_bins + auprc.bin_size = 200 + auprc.agg_function = "max" + auprc.agg_threshold = 0.5 + auprc.peak_based = True + auprc.blacklist_mask = np.ones(n_bins, dtype=bool) + auprc.goldstandard_stream = _StubGoldStandard(gold_standard) + auprc.prediction_array = np.random.default_rng(5).random(n_bins) + gold_standard + auprc.results_location = str(tmp_path / "chr1_PRC.tsv") + + auprc.__import_goldstandard_array__() + auprc.__AUPRC__() + + results = pd.read_csv(auprc.results_location, sep="\t").iloc[0] + member = peak_gs_array_to_member_array(gold_standard > 0) + + assert results["Total_GoldStandard_Peaks"] == 100 + assert results["Random_AUPRC"] == pytest.approx(random_aup_ucper(member)) + assert results["Random_Precision_at_10_Percent_Recall"] == pytest.approx(random_precision_at_ucper(member, 0.1)) + assert results["log2FC_Precision_at_10_Percent_Recall_Random"] == pytest.approx( + np.log2(results["Precision_at_10_Percent_Recall"] / results["Random_Precision_at_10_Percent_Recall"])) + + +class _StubGoldStandardBigWig(_StubGoldStandard): + """pyBigWig stand-in with a chromosome size, for running ChromosomeAUPRC.__init__""" + + def chroms(self, chromosome): + return len(self.bins) * 200 + + +def test_random_only_writes_just_the_two_random_baselines_without_reading_the_prediction(tmp_path, monkeypatch): + import pandas as pd + from maxatac.utilities import benchmarking_tools + from maxatac.utilities.benchmarking_tools import (ChromosomeAUPRC, peak_gs_array_to_member_array, + random_aup_ucper, random_precision_at_ucper) + + gold_standard = _peak_gold_standard([1, 2, 3, 5, 8] * 20, 30, np.random.default_rng(6)).astype(float) + n_bins = len(gold_standard) + # Blacklist the first 50 bins: the baselines must use the masked gold standard only + mask = np.ones(n_bins, dtype=bool) + mask[:50] = False + + opened = [] + + def load_bigwig(path): + opened.append(path) + return _StubGoldStandardBigWig(gold_standard) + + monkeypatch.setattr(benchmarking_tools, "load_bigwig", load_bigwig) + monkeypatch.setattr(benchmarking_tools, "chromosome_blacklist_mask", lambda *args: mask) + + results_location = str(tmp_path / "test_chr1_200bp_random_UCPeR.tsv") + ChromosomeAUPRC(None, "gold_standard.bw", "blacklist.bw", None, "chr1", 200, "max", 0.5, + results_location, 9, peak_based=True, random_only=True) + + results = pd.read_csv(results_location, sep="\t") + member = peak_gs_array_to_member_array(gold_standard[mask] > 0) + + assert opened == ["gold_standard.bw"] + assert list(results.columns) == ["Random_AUPRC", "Random_Precision_at_10_Percent_Recall"] + assert len(results) == 1 + assert results["Random_AUPRC"].iloc[0] == pytest.approx(random_aup_ucper(member)) + assert results["Random_Precision_at_10_Percent_Recall"].iloc[0] == pytest.approx(random_precision_at_ucper(member, 0.1)) + + +def test_random_only_requires_peak_based(): + from maxatac.utilities.benchmarking_tools import ChromosomeAUPRC + + with pytest.raises(ValueError, match="peak_based"): + ChromosomeAUPRC(None, "gold_standard.bw", None, None, "chr1", 200, "max", 0.5, + "out.tsv", 9, peak_based=False, random_only=True) + + +def test_parse_benchmark_random_needs_no_prediction_but_needs_peak_based(): + parser_module = pytest.importorskip("maxatac.utilities.parser") + base = ["benchmark", "--gold_standard", "average.bigwig", "--name", "benchmark_test"] + + args = parser_module.parse_arguments(base + ["--peak_based", "--random"], DATA_FOLDER) + assert args.random and args.peak_based and args.prediction is None + + with pytest.raises(SystemExit): + parser_module.parse_arguments(base + ["--random"], DATA_FOLDER) + + with pytest.raises(SystemExit): + parser_module.parse_arguments(base + ["--peak_based"], DATA_FOLDER) + + +def test_pct_rank_gives_tied_bins_the_lowest_rank_and_zero_or_missing_bins_zero(): + from maxatac.utilities.genome_tools import _pct_rank + + # 6 bins: a zero, a NaN, a tie at 0.5, 0.2 and 0.9 + percentile = _pct_rank(np.array([0.0, np.nan, 0.5, 0.5, 0.2, 0.9])) + + # rankdata(min) over [0, 0, 0.5, 0.5, 0.2, 0.9] -> [1, 1, 4, 4, 3, 6], / 6; zero and NaN bins forced to 0 + np.testing.assert_allclose(percentile, np.array([0, 0, 4, 4, 3, 6]) / 6) + + +def test_rank_max_takes_the_max_percentile_and_falls_back_to_the_other_track(): + from maxatac.utilities.genome_tools import combine_prediction_arrays + + # Model scores are small, the average ChIP signal is large: a raw max would always pick the average + model = np.array([0.01, 0.02, 0.03, np.nan, 0.0, 0.04]) + average = np.array([10.0, 50.0, 0.0, 30.0, 20.0, 40.0]) + + combined = combine_prediction_arrays(model, average, combine_operation="rank_max") + + # model percentiles: [3, 4, 5, 0, 0, 6] / 6 (NaN and zero bins -> 0) + # average percentiles: [2, 6, 0, 4, 3, 5] / 6 (zero bin -> 0) + np.testing.assert_allclose(combined, np.array([3, 6, 5, 4, 3, 6]) / 6) + np.testing.assert_allclose(combine_prediction_arrays(model, average, combine_operation="max"), + np.array([10.0, 50.0, 0.03, 30.0, 20.0, 40.0])) + + +def test_rank_max_with_all_zero_or_missing_bins_scores_them_zero(): + from maxatac.utilities.genome_tools import combine_prediction_arrays + + combined = combine_prediction_arrays(np.array([np.nan, 0.0, 0.3]), np.array([0.0, np.nan, np.nan]), + combine_operation="rank_max") + + np.testing.assert_allclose(combined, np.array([0.0, 0.0, 1.0])) + + +def test_rank_max_logs_how_often_each_track_supplies_the_max(caplog): + import logging + from maxatac.utilities.genome_tools import combine_prediction_arrays + + with caplog.at_level(logging.INFO): + combine_prediction_arrays(np.array([0.01, 0.02, 0.03, np.nan, 0.0, 0.04]), + np.array([10.0, 50.0, 0.0, 30.0, 20.0, 40.0]), + combine_operation="rank_max") + + # From the percentiles above: model wins bins 1, 3, 6 and the average wins bins 2, 4, 5 + assert "primary supplies the max in 50.00% of bins, alternative in 50.00%, tied in 0.00%" in caplog.text + + +class _StubPredictionBigWig(_StubGoldStandardBigWig): + """pyBigWig stand-in for a prediction track; keeps NaN for missing bins like import_bigwig_stats_array expects""" + + +def test_chromosome_auprc_benchmarks_the_rank_max_ensemble(tmp_path, monkeypatch): + import pandas as pd + from maxatac.utilities import benchmarking_tools + from maxatac.utilities.benchmarking_tools import ChromosomeAUPRC + from maxatac.utilities.genome_tools import combine_prediction_arrays + + rng = np.random.default_rng(7) + gold_standard = _peak_gold_standard([1, 2, 3] * 30, 20, rng).astype(float) + n_bins = len(gold_standard) + + # Model: weak signal on peaks, missing on 5% of bins. Average ChIP: large values, zero on 40% of bins + model = rng.random(n_bins) * 0.1 + 0.05 * gold_standard + model[rng.random(n_bins) < 0.05] = np.nan + average = rng.random(n_bins) * 100 * (rng.random(n_bins) > 0.4) + + streams = {"model.bw": _StubPredictionBigWig(model), + "average.bw": _StubPredictionBigWig(average), + # --agg sum returns base-pair totals: 200 for a fully covered 200 bp bin + "gold_standard.bw": _StubGoldStandardBigWig(gold_standard * 200)} + monkeypatch.setattr(benchmarking_tools, "load_bigwig", lambda path: streams[path]) + # Blacklist bins 0-19, whitelist everything else but the last 10 bins + keep = np.ones(n_bins, dtype=bool) + keep[:20] = False + monkeypatch.setattr(benchmarking_tools, "chromosome_blacklist_mask", lambda *args: keep) + whitelist = np.ones(n_bins, dtype=bool) + whitelist[-10:] = False + monkeypatch.setattr(benchmarking_tools, "chromosome_whitelist_mask", lambda *args: whitelist) + + auprc = ChromosomeAUPRC("model.bw", "gold_standard.bw", "blacklist.bw", "whitelist.bw", "chr1", 200, "sum", 0.5, + str(tmp_path / "chr1_PRC.tsv"), 9, peak_based=True, + alternative_prediction_bw="average.bw", prediction_combine_operation="rank_max") + + # Combined on all bins before masking, and not divided by bin_size under --agg sum + expected = np.round(combine_prediction_arrays(model, average, combine_operation="rank_max"), 9) + np.testing.assert_allclose(auprc.prediction_array, expected) + assert auprc.prediction_array.max() <= 1.0 + + np.testing.assert_array_equal(auprc.blacklist_mask, keep & whitelist) + results = pd.read_csv(tmp_path / "chr1_PRC.tsv", sep="\t") + assert 0 < results["AUPRC"].iloc[0] <= 1 + + +def test_quant_benchmark_rejects_rank_max(monkeypatch): + from maxatac.utilities import benchmarking_tools + + stub = _StubGoldStandardBigWig(np.zeros(10)) + monkeypatch.setattr(benchmarking_tools, "load_bigwig", lambda path: stub) + + with pytest.raises(ValueError, match="rank_max"): + benchmarking_tools.calculate_R2_pearson_spearman("model.bw", "gs.bw", "quant_gs.bw", "chr1", 200, "mean", + "out.tsv", None, None, "null.bw", + alternative_prediction_bw="average.bw", + prediction_combine_operation="rank_max") + + +def test_parse_benchmark_rank_max_is_rejected_with_quant(): + parser_module = pytest.importorskip("maxatac.utilities.parser") + base = ["benchmark", "--bw", "model.bw", "--alternative_prediction", "average.bw", + "--gold_standard", "gs.bw", "--name", "benchmark_test", "--prediction_combine_operation", "rank_max"] + + assert parser_module.parse_arguments(base + ["--peak_based"], DATA_FOLDER).prediction_combine_operation == "rank_max" + + with pytest.raises(SystemExit): + parser_module.parse_arguments(base + ["--quant", "--quant_gold_standard", "q.bw", "--quant_gs_null", "n.bw"], + DATA_FOLDER) diff --git a/tests/test_data.py b/tests/test_data.py deleted file mode 100644 index 421cd8e..0000000 --- a/tests/test_data.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -import re -import hashlib - -from maxatac.utilities.system_tools import get_files - -# Directory with all input files for testing. -# Subfolders are not allowed due to possible file name duplicates. -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - - -CONTROL_MD5_SUMS = { - "hg19.2bit": "bcdbfbe9da62f19bee88b74dabef8cd3", - "train_signal_cell_A549.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "validate_signal_cell_HCT116.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "validate_sites_cell_HCT116_tf_CTCF.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "average.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "predict_signal_cell_GM12878.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "train_sites_cell_A549_tf_CTCF.bigwig": "d41d8cd98f00b204e9800998ecf8427e", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed": "63c2fda65d6810d4194e92c8ea8e394d" -} - - -def get_md5_sum(location, block_size=2**20): - md5_sum = hashlib.md5() - with open(location , "rb") as input_stream: - while True: - buf = input_stream.read(block_size) - if not buf: - break - md5_sum.update(buf) - return md5_sum.hexdigest() - - -def test_md5_sum(): - collected_md5_sums = {} - for filename, location in get_files(DATA_FOLDER).items(): - collected_md5_sums[filename] = get_md5_sum(location) - for filename, control_md5_sum in CONTROL_MD5_SUMS.items(): - assert filename in collected_md5_sums, "missing input file for tests" - assert collected_md5_sums[filename] == control_md5_sum, "change input file for tests" diff --git a/tests/test_helpers.py b/tests/test_helpers.py deleted file mode 100644 index de84de6..0000000 --- a/tests/test_helpers.py +++ /dev/null @@ -1,60 +0,0 @@ -import pytest -import os - -from maxatac.utilities.system_tools import get_files - - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - - -control_empty = [] - -control_all_files = [ - "hg19.2bit", - "train_signal_cell_A549.bigwig", - "validate_signal_cell_HCT116.bigwig", - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "average.bigwig", - "predict_signal_cell_GM12878.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" -] - -control_all_bigwigs = [ - "train_signal_cell_A549.bigwig", - "validate_signal_cell_HCT116.bigwig", - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "average.bigwig", - "predict_signal_cell_GM12878.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" -] - -control_all_2bit = [ - "hg19.2bit" -] - -control_files_by_names = [ - "hg19.2bit", - "average.bigwig", - "predict_signal_cell_GM12878.bigwig", -] - -control_file_by_name = [ - "hg19.2bit" -] - - -@pytest.mark.parametrize( - "filename_pattern, control_filenames", - [ - (None, control_all_files), - (".*bigwig", control_all_bigwigs), - (".*2bit", control_all_2bit), - ("hg19.2bit|average.bigwig|predict_signal_cell_GM12878.bigwig", control_files_by_names), - ("hg19.2bit", control_file_by_name), - ("mm10", control_empty) - ] -) -def test_get_files(filename_pattern, control_filenames): - collected_filenames = get_files(DATA_FOLDER, filename_pattern).keys() - assert sorted(collected_filenames) == sorted(control_filenames) diff --git a/tests/test_normalize/test_normalize.py b/tests/test_normalize/test_normalize.py deleted file mode 100644 index a7e1f64..0000000 --- a/tests/test_normalize/test_normalize.py +++ /dev/null @@ -1,41 +0,0 @@ -import os -import pytest -from maxatac.analyses.normalize import run_normalization -from maxatac.utilities.system_tools import Namespace -import subprocess -from maxatac.utilities.constants import blacklist_bigwig_path, AUTOSOMAL_CHRS, chrom_sizes_path -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -input_file_paths = "../data/average/IMR-90_all_chrom.bw" - -expected_outputs = {"../data/normalize/IMR-90_minmax01_percentile99.bw": "413b925d425b039ff3ac46d84bd790c9", - "../data/normalize/IMR-90_minmax01_percentile99_genome_stats.txt": "cb54a14503617564674d1ba398a8e05e", - "../data/normalize/IMR-90_minmax01_percentile99_chromosome_min_max.txt": "19185afdd98c18ab03c891ed9f51f06c"} - -args_test_min_max = Namespace(signal=input_file_paths, - output_dir=DATA_FOLDER, - name="normalize_test", - max=False, - method="min-max", - max_percentile=99, - blacklist=blacklist_bigwig_path, - chromosomes=AUTOSOMAL_CHRS, - chrom_sizes=chrom_sizes_path, - clip=False) - - -def test_normalization(): - """ - Test that maxatac normalize can min-max normalize a bigwig file to the 99th percentile max - - """ - run_normalization(args_test_min_max) - - output_file = os.path.join(DATA_FOLDER, "normalize_test.bw") - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == expected_outputs["../data/normalize/IMR-90_minmax01_percentile99.bw"] - diff --git a/tests/test_parser.py b/tests/test_parser.py deleted file mode 100644 index 0fa0680..0000000 --- a/tests/test_parser.py +++ /dev/null @@ -1,1795 +0,0 @@ -import pytest -import os - -from maxatac.utilities.system_tools import get_files -from maxatac.utilities.parser import ( - get_synced_chroms, - parse_arguments -) - - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - - -@pytest.mark.parametrize( - "chroms, filenames, ignore_regions, control_synced_chroms", - [ - # correct inputs without regions - ( - [], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {} - ), - ( - [], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - - # correct inputs with regions - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 100]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [10, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-249250621"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - - # not correct inputs without regions - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {} - ), - ( - ["chrA"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {} - ), - - # not correct inputs with regions - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:-100-100"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:100-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-500000000"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:0-0"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - False, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - ( - ["chr1:10-10"], - [ - "hg19.2bit", - "predict_signal_cell_GM12878.bigwig", - "average.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - {"chr1": {"length": 249250621, "region": [0, 249250621]}} - ), - - # combination of mutiple files - ( - ["chr1"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - {} - ), - ( - ["chr1"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chr2"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - {"chr2": {"length": 243199373, "region": [0, 243199373]}} - ), - ( - ["chr2"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {"chr2": {"length": 243199373, "region": [0, 243199373]}} - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [10, 100]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr1", "chr2", "chr3:10-100"], - [ - "hg19.2bit", - "average.bigwig", - "train_signal_cell_A549.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - True, - { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]} - } - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig" - ], - None, - {} - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - None - ], - None, - {} - ), - ( - ["chr1"], - [ - "validate_sites_cell_HCT116_tf_CTCF.bigwig", - "train_sites_cell_A549_tf_CTCF.bigwig", - None, - "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed" - ], - None, - {} - ) - ] -) -def test_get_synced_chroms(chroms, filenames, ignore_regions, control_synced_chroms): - locations = list(get_files(DATA_FOLDER, "|".join([f for f in filenames if f is not None])).values()) - locations += [f for f in filenames if f is None] - synced_chroms = get_synced_chroms(chroms, locations, ignore_regions) - assert synced_chroms == control_synced_chroms - - -# For not direct testing of assert_and_fix_args_for_training - -@pytest.mark.parametrize( - "args, control_args", - [ - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr2", "chr8", "chr21", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr2", "chr8", "chr21", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]}, - "chr21": {"length": 48129895, "region": [0, 48129895]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": {}, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr2", "chr3", "chr10", "chr11", "chr8", "chr21", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": {}, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr8": {"length": 146364022, "region": [0, 146364022]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": { - "chr8": {"length": 146364022, "region": [0, 146364022]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": {}, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": {}, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--filters", "average.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--filters", "average.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr12", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr2": {"length": 243199373, "region": [0, 243199373]}, - "chr3": {"length": 198022430, "region": [0, 198022430]}, - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]}, - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]}, - "chr11": {"length": 135006516, "region": [0, 135006516]} - }, - "vchroms": { - "chr12": {"length": 133851895, "region": [0, 133851895]}, - "chr13": {"length": 115169878, "region": [0, 115169878]} - } - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": {} - } - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--filters", "train_sites_cell_A549_tf_CTCF.bigwig", - "--tchroms", "chr10", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "validate_sites_cell_HCT116_tf_CTCF.bigwig" - ], - { - "chroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "tchroms": { - "chr10": {"length": 135534747, "region": [0, 135534747]} - }, - "vchroms": {} - } - ) - ] -) -def test_parse_chromosome_arguments_for_training(args, control_args): - args = parse_arguments(args, DATA_FOLDER) - assert args.chroms == control_args["chroms"] and args.tchroms == control_args["tchroms"] and args.vchroms == control_args["vchroms"] - - -# For not direct testing of assert_and_fix_args_for_training (should fail on assert) - -@pytest.mark.parametrize( - "args", - [ - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr10", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr20", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr2", "chr3", "chr1", "chr10", "chr11", "chr8", "chr12", "chr13", - "--tchroms", "chr1", "chr20", "chr11", - "--vchroms", "chr8", "chr10", "chr13", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tchroms", "chr1", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tchroms", "chr1", - "--vchroms", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ), - ( - [ - "train", - "--signal", "train_signal_cell_A549.bigwig", - "--validation", "validate_signal_cell_HCT116.bigwig", - "--average", "average.bigwig", - "--preferences", "GSE143104_ENCFF551HTC_pseudoreplicated_IDR_thresholded_peaks_hg19.bigBed", - "--sequence", "hg19.2bit", - "--chroms", "chr1", "chr8", - "--tsites", "train_sites_cell_A549_tf_CTCF.bigwig", - "--vsites", "train_sites_cell_A549_tf_CTCF.bigwig" - ] - ) - ] -) -def test_parse_chromosome_arguments_for_training_should_fail(args): - with pytest.raises(AssertionError): - args = parse_arguments(args, DATA_FOLDER) - - - - -# average.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753) -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# predict_signal_cell_GM12878.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747) -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753 -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# train_signal_cell_A549.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753) -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# train_sites_cell_A549_tf_CTCF.bigwig -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067) -# chr7 159138663 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753 -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr22 51304566 -# chrX 155270560 - - -# validate_signal_cell_HCT116.bigwig -# chr1 249250621 -# chr2 243199373 -# chr3 198022430 -# chr4 191154276 -# chr5 180915260 -# chr6 171115067 -# chr7 159138663 -# chr8 146364022 -# chr9 141213431 -# chr10 135534747 -# chr11 135006516 -# chr12 133851895 -# chr13 115169878 -# chr14 107349540 -# chr15 102531392 -# chr16 90354753) -# chr17 81195210 -# chr18 78077248 -# chr19 59128983 -# chr20 63025520 -# chr21 48129895 -# chr22 51304566 -# chrX 155270560 - - -# validate_sites_cell_HCT116_tf_CTCF.bigwig -# chr1 249250621 -# chr8 146364022 -# chr21 48129895 \ No newline at end of file diff --git a/tests/test_predict/test_predict.py b/tests/test_predict/test_predict.py deleted file mode 100644 index d400e5f..0000000 --- a/tests/test_predict/test_predict.py +++ /dev/null @@ -1,33 +0,0 @@ -import os -import pytest -import pandas as pd -from maxatac.utilities.prepare_tools import convert_fragments_to_tn5_bed -from maxatac.analyses.prepare import run_prepare -from maxatac.utilities.constants import chrom_sizes_path, AUTOSOMAL_CHRS, blacklist_bigwig_path, blacklist_path - -from maxatac.utilities.system_tools import Namespace -import subprocess - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -# These are for the bulk data sets -input_bw_path = "/Users/caz3so/workspaces/miraldiLab/maxATAC/tests/data/prepare/bulk_atac_SRX2717911_sub01.bam" - -expected_outputs = {"GM12878_bulk_IS_slop20_RP20M.bw": "c49a30be1da68b73141ba02a2255a0f6", - "GM12878_bulk_IS_slop20_RP20M_minmax01.bw": "e0429a7fb990da36707a075343b97b3e", - "GM12878_bulk_IS_slop20_RP20M_minmax01_chromosome_min_max.txt": "36e5f37a4ec1aaea0fb55ed1c86e12ee", - "GM12878_bulk_IS_slop20_RP20M_minmax01_genome_stats.txt": "b366a2c759587d24440f25c6343caae6"} - -# These are for the scATAC-seq processing functions -input_file_path = "../data/prepare/scatac_fragments.tsv" -expected_file_path = "../data/prepare/scatac_CutSites.tsv" - - -def test_fragments_to_tn5_bed(): - """ - Test that fragments are converted to cut sites correctly - - """ - assert convert_fragments_to_tn5_bed(fragments_tsv=input_file_path, - chroms=["chr1"] - ).equals(expected_dataframe) \ No newline at end of file diff --git a/tests/test_prepare/test_prepare.py b/tests/test_prepare/test_prepare.py deleted file mode 100644 index 475077b..0000000 --- a/tests/test_prepare/test_prepare.py +++ /dev/null @@ -1,117 +0,0 @@ -import os -import pytest -import pandas as pd -from maxatac.utilities.prepare_tools import convert_fragments_to_tn5_bed -from maxatac.analyses.prepare import run_prepare -from maxatac.utilities.constants import chrom_sizes_path, AUTOSOMAL_CHRS, blacklist_bigwig_path, blacklist_path - -from maxatac.utilities.system_tools import Namespace -import subprocess - -DATA_FOLDER = os.path.abspath(os.path.join(os.path.dirname(__file__), "temp")) - -# These are for the bulk data sets -input_bam_path = "/Users/caz3so/workspaces/miraldiLab/maxATAC/tests/data/prepare/bulk_atac_SRX2717911_sub01.bam" - -expected_bulk_outputs = {"GM12878_bulk_IS_slop20_RP20M.bw": "c49a30be1da68b73141ba02a2255a0f6", - "GM12878_bulk_IS_slop20_RP20M_minmax01.bw": "e0429a7fb990da36707a075343b97b3e", - "GM12878_bulk_IS_slop20_RP20M_minmax01_chromosome_min_max.txt": "36e5f37a4ec1aaea0fb55ed1c86e12ee", - "GM12878_bulk_IS_slop20_RP20M_minmax01_genome_stats.txt": "b366a2c759587d24440f25c6343caae6"} - -# These are for the scATAC-seq processing functions -input_file_path = "../data/prepare/scatac_fragments.tsv" -expected_file_path = "../data/prepare/scatac_CutSites.tsv" -expected_dataframe = pd.read_table(expected_file_path, sep="\t") - -# Full scATAC fragment file test -input_scatac_frags = "/Users/caz3so/workspaces/miraldiLab/maxATAC/tests/data/prepare/GM12878_fragments_subsample_1M.tsv" - -expected_scatac_outputs = {"GM12878_scatac_1M_IS_slop20_RP20M.bw": "5ad8c991d458e74f96024337652c93b3", - "GM12878_scatac_1M_IS_slop20_RP20M_minmax01.bw": "04b7edda09ec6303d80c121109bad90e", - "GM12878_scatac_1M_IS_slop20_RP20M_minmax01_chromosome_min_max.txt": "25863a4d1b83e7410dbaae0fa6090d59", - "GM12878_scatac_1M_IS_slop20_RP20M_minmax01_genome_stats.txt": "a7397bf4c5ef4dd4c79aaab35830ff4d"} - - -def test_fragments_to_tn5_bed(): - """ - Test that fragments are converted to cut sites correctly - - """ - assert convert_fragments_to_tn5_bed(fragments_tsv=input_file_path, - chroms=["chr1"]).equals(expected_dataframe) - - -def test_fragments_to_tn5_bed_wrong_chrom(): - """ - Test that fragments can be filtered by chromosome - - """ - assert (convert_fragments_to_tn5_bed(fragments_tsv=input_file_path, - chroms=["chr2"]).equals(expected_dataframe) == False) - - -def test_prepare_bulk(): - """ - Test that a bam file can be prepared for maxATAC - """ - # Args for bulk - args_bulk = Namespace(input=input_bam_path, - output_dir=DATA_FOLDER, - name="GM12878_bulk", - chromosomes=AUTOSOMAL_CHRS, - chrom_sizes=chrom_sizes_path, - slop=20, - rpm_factor=20000000, - blacklist_bed=blacklist_path, - blacklist=blacklist_bigwig_path, - threads=4, - skip_dedup=False, - clip=False, - max=False, - method="min-max", - max_percentile=99) - - run_prepare(args_bulk) - - for file, md5 in expected_bulk_outputs.items(): - output_file = os.path.join(DATA_FOLDER, file) - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == md5 - - -def test_prepare_scatac(): - """ - Test that a tsv file can be prepared for maxATAC - """ - # Args for scatac - args_scatac = Namespace(input=input_scatac_frags, - output_dir=DATA_FOLDER, - name="GM12878_scatac_1M", - chromosomes=AUTOSOMAL_CHRS, - chrom_sizes=chrom_sizes_path, - slop=20, - rpm_factor=20000000, - blacklist_bed=blacklist_path, - blacklist=blacklist_bigwig_path, - threads=4, - skip_dedup=False, - clip=False, - max=False, - method="min-max", - max_percentile=99 - ) - - run_prepare(args_scatac) - - for file, md5 in expected_scatac_outputs.items(): - output_file = os.path.join(DATA_FOLDER, file) - - results = subprocess.run(f"md5sum {output_file}", shell=True, capture_output=True) - - md5sum = str(results.stdout.decode()).split(" ")[0] - - assert md5sum == md5 diff --git a/tests/test_requirements.txt b/tests/test_requirements.txt deleted file mode 100644 index 5a59c47..0000000 --- a/tests/test_requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -pytest==6.2.5 -pytest-xdist==2.4.0 -pytest-cov==3.0.0 -coveralls==3.2.0 \ No newline at end of file diff --git a/tests/test_threshold.py b/tests/test_threshold.py new file mode 100644 index 0000000..974d909 --- /dev/null +++ b/tests/test_threshold.py @@ -0,0 +1,77 @@ +import numpy as np +import pandas as pd +import pytest + +from maxatac.utilities.peak_tools import get_threshold +from maxatac.utilities.threshold_tools import compute_calibration_curve, PEAK_RECALL + + +def _actual_metrics(goldstandard, prediction, threshold): + """Precision and recall at a threshold, with sklearn's >= rule""" + called = prediction >= threshold + true_positives = np.count_nonzero(called & goldstandard) + return true_positives / np.count_nonzero(called), true_positives / np.count_nonzero(goldstandard) + + +def test_calibration_curve_keeps_only_attained_thresholds(): + # Real precision: 0.667 at threshold 0.1, 0.5 at 0.2, 0 at 0.9 (the top-scoring bin is unbound). + # 0.2 and 0.9 are beaten by 0.1, and the (Precision=1, Recall=0) sentinel is not a threshold + curve = compute_calibration_curve(np.array([1, 1, 0]), np.array([0.1, 0.2, 0.9])) + + assert curve["Threshold"].tolist() == [0.1] + assert curve["Precision"].tolist() == pytest.approx([2 / 3]) + assert curve["Recall"].tolist() == pytest.approx([1.0]) + assert (curve["Precision"] < 1).all() + + +def test_calibration_curve_rows_are_real_and_monotonic(): + rng = np.random.default_rng(0) + goldstandard = rng.random(500) < 0.2 + prediction = np.round(goldstandard * 0.3 + rng.random(500), 3) + peak_max = rng.random(40) + + curve = compute_calibration_curve(goldstandard, prediction, peak_max=peak_max) + + # Every row is the precision/recall actually achieved at its own threshold + for row in curve.itertuples(): + precision, recall = _actual_metrics(goldstandard, prediction, row.Threshold) + assert row.Precision == pytest.approx(precision) + assert row.Recall == pytest.approx(recall) + + # Ascending threshold: precision strictly rises, recall and Peak_Recall never rise + curve = curve.sort_values("Threshold") + assert np.all(np.diff(curve["Precision"]) > 0) + assert np.all(np.diff(curve["Recall"]) <= 0) + assert np.all(np.diff(curve[PEAK_RECALL]) <= 0) + + +def _write_table(path, rows): + pd.DataFrame(rows, columns=["Metric", "Bin", "Precision", "Recall", "Threshold", "F1"]).to_csv( + path, sep="\t", index=False) + return str(path) + + +def test_get_threshold_requires_the_achieved_value(tmp_path): + # Grid extension: bins past the best precision (0.8) repeat its row, so Bin 1.0 holds Precision 0.8 + table = _write_table(tmp_path / "table.tsv", [ + ["Precision", 0.70, 0.70, 0.60, 0.5, 0.65], + ["Precision", 0.80, 0.80, 0.40, 0.7, 0.53], + ["Precision", 0.90, 0.80, 0.40, 0.7, 0.53], + ["Precision", 1.00, 0.80, 0.40, 0.7, 0.53], + ]) + + with pytest.raises(ValueError, match="highest Precision it reaches is 0.800"): + get_threshold(table, "Precision", 1.0) + + # Closest achieved value that meets the request + assert get_threshold(table, "Precision", 0.75) == pytest.approx(0.7) + assert get_threshold(table, "Precision", 0.65) == pytest.approx(0.5) + + +def test_get_threshold_breaks_ties_on_f1(tmp_path): + table = _write_table(tmp_path / "table.tsv", [ + ["Recall", 0.50, 0.60, 0.50, 0.9, 0.545], + ["Recall", 0.51, 0.70, 0.50, 0.8, 0.583], + ]) + + assert get_threshold(table, "Recall", 0.5) == pytest.approx(0.8) diff --git a/tests/test_tools.py b/tests/test_tools.py deleted file mode 100644 index 804281e..0000000 --- a/tests/test_tools.py +++ /dev/null @@ -1,20 +0,0 @@ -import pytest -import os -from maxatac.utilities.system_tools import get_files -from maxatac.utilities.constants import DATA_FOLDER - -control_all_2bit = [ - "hg19.2bit" -] - - -@pytest.mark.parametrize( - "filename_pattern, control_filenames", - [ - ("hg38.2bit", control_all_2bit), - ] -) - -def test_get_one_hot_encoded(filename_pattern, control_filenames): - collected_filenames = get_files(DATA_FOLDER, filename_pattern).keys() - assert sorted(collected_filenames) == sorted(control_filenames)